Comparison operators are used to compare two values (number or string). These operators are the backbone of logical decision-making in PHP—they always return a Boolean result (TRUE or FALSE).
The following table lists the comparison operators supported by PHP:
| Operator | Name | Description |
|---|---|---|
== |
Equal | Returns true if $x is equal to $y |
=== |
Identical | Returns true if $x is equal to $y, **and they are of the same type** |
!= |
Not equal | Returns true if $x is not equal to $y |
!== |
Not identical | Returns true if $x is not equal to $y, or they are not of the same type |
> |
Greater than | Returns true if $x is greater than $y |
< |
Less than | Returns true if $x is less than $y |
>= |
Greater than or equal to | Returns true if $x is greater than or equal to $y |
<= |
Less than or equal to | Returns true if $x is less than or equal to $y |
<=> |
Spaceship | Returns an integer less than, equal to, or greater than zero, depending on if $x is less than, equal to, or greater than $y. |
This is one of the most important concepts for PHP developers to master. While == only checks the value, === checks both the value and the data type.
<?php
$x = 100;
$y = "100";
var_dump($x == $y); // bool(true) - because values are equal
var_dump($x === $y); // bool(false) - because types are different (int vs string)
?>
Introduced in PHP 7, the spaceship operator is used for comparing two expressions. It returns:
<?php
echo 5 <=> 10; // Outputs: -1
echo 10 <=> 10; // Outputs: 0
echo 10 <=> 5; // Outputs: 1
?>
=== over ==. Strict comparison prevents "weird" PHP behavior where strings might be unexpectedly converted to numbers.