Skip to Content
Learn
Logical Operators and Compound Conditions
The Not Operator

The logical not operator (!) takes only a right operand. It reverses the boolean value of its operand.

!TRUE; // Evaluates to: FALSE !FALSE; // Evaluates to: TRUE

The not operator has very high operator precedence; be sure to use parentheses so that code evaluation happens as intended:

!10 < 11; // Evaluates to: TRUE !(10 < 11); // Evaluates to: FALSE !TRUE || TRUE; // Evaluates to: TRUE !(TRUE || TRUE); // Evaluates to: FALSE

The not operator is useful when we only want to take a course of action if a condition is not true. For example, if a user is not logged in, a web application may show a pop-up telling them they must do so to continue.

$is_logged_in = FALSE; if (!$is_logged_in){ echo "You must log in to continue."; }

We could accomplish this same functionality without using the ! operator, but look at how much more cumbersome that code is:

$is_logged_in = FALSE; if ($is_logged_in){ // Do nothing... } else { echo "You must log in to continue."; }

Let’s practice using the not operator!

Instructions

1.

Let’s play Duck, Duck, Goose. Write a function, duckDuckGoose().

Your function should have one boolean parameter, $is_goose. If $is_goose is FALSE, your function should return "duck". Otherwise, it should return "goose!"

There are several ways you could accomplish this functionality, but since we’re practicing using the ! operator, be sure to use it.

2.

Invoke your function three times and use echo to print the results to the terminal. The first two invocations should result in "duck" being printed, and the third should result in "goose!" being printed.

Folder Icon

Take this course for free

Already have an account?