Comparison Operators
Explore the use of comparison operators in PHP to evaluate and compare values effectively. Understand the difference between equal and identical operators, and how the spaceship operator works to simplify comparisons. This lesson helps you apply these operators correctly in your code.
We'll cover the following...
Basic operators
Comparison operators, as the name suggests, allow you to compare two values. The following table illustrates the different comparison operators in PHP:
| Operator | Name | Example |
|---|---|---|
| == | Equal | a==b |
| === | Identical | a===b |
| != | Not Equal | a!=b |
| !== | Not Identical | a!==b |
| < | Less than | a<b |
| > | Greater than | a>b |
| <= | Less than equal to | a<=b |
| >= | Greater than equal to | a>=b |
Note: For basic equality testing, the equal operator
==is used. For more comprehensive checks, use the identical operator===.
For instance, the == operator will return true when an integer 4 is compared with a character '4' but the === will return false. Run the code snippet below to see how this works:
In the above code snippet, the == operator returns true because the character '4' is cast to an integer.
Spaceship Operator
The spaceship operator (<=>) is a special kind of comparison operator. It
- returns
-1if first expression is lesser than the second expression. - returns
1if the first expression is greater than the second expression. - returns
0if the first expression is equal to the second expression.
Run the code snippet below to see how it works
Remember: Objects are not comparable, and doing so will result in undefined behavior.
Quick Quiz on Comparison Operators
What is the result of the following code?
<?php
$a = 5;
$b = 2;
$c = 4;
if ($a < $b + $c)
{
echo $a<=>($c - $b);
}
else
{
echo ($c - $b) <=>$a;
}
?>
0
1
-1
Now, let’s move on to logical operators in the next lesson.