Skip to main content

Comparison Operators

A condition usually comes down to comparing two values, and that is the job of comparison operators.

Equal Operator

Use == to test whether two values are equal. The result is true when they are:

Prompt
Write a PHP script that uses the == operator to check if a variable equals a value and prints a message if true.
Output: PHP script

Greater Than Operator

With >, you get true when the value on the left is the bigger of the two:

Prompt
Write a PHP script that uses the > operator to check if one variable is greater than another and prints a message.
Output: PHP script

Less Than Operator

With <, it works the other way round: the result is true when the value on the left is the smaller one:

Prompt
Write a PHP script that uses the < operator to check if one variable is less than another and prints a message.
Output: PHP script

Logical Operators

To build one condition out of several smaller ones, you need logical operators.

And Operator

&& gives true only when the conditions on both sides are true:

Prompt
Write a PHP script that uses the && operator to check if two conditions are both true and prints a message.
Output: PHP script

Or Operator

|| needs just one true condition, though both may be true:

Prompt
Write a PHP script that uses the || operator to check if at least one of two conditions is true and prints a message.
Output: PHP script

Not Operator

! flips a condition, so the if block runs when the condition in the parentheses is false:

Prompt
Write a PHP script that uses the ! operator to check if a condition is not true and prints a message.
Output: PHP script