PHP Reference ยท Operators
PHP comparison operators
Reference for PHP comparison operators: ==, ===, !=, !==, <, >, <=, >= and the spaceship <=>, with PHP 8 type juggling rules and common traps.
Comparison operators compare two values and return a boolean, except the spaceship operator <=>, which returns -1, 0 or 1. == compares after type juggling, === also requires the same type.
Prefer === and !== in almost all code. Loose comparison is convenient for numeric strings, but it can surprise you when strings, numbers, null and booleans meet.
var_dump(5 == "5"); // true var_dump(5 === "5"); // false echo 1 <=> 2; // -1
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
$a == $b $a === $b $a != $b $a <> $b $a !== $b $a < $b $a > $b $a <= $b $a >= $b $a <=> $b
| Operator | True when |
|---|---|
== |
Equal after type juggling |
=== |
Same value and same type (for objects, the same instance) |
!=, <> |
Not equal after juggling |
!== |
Not identical |
<, >, <=, >= |
Ordering after juggling |
<=> |
Returns an integer less than, equal to or greater than zero |
Usage notes
- PHP 8 string-to-number rule. Number versus a non-numeric string compares the number as a string. So
0 == "a"isfalsein PHP 8 (it wastruebefore). Two numeric strings are compared as numbers:"10" == "1e1"istrue. nulland booleans. Loose comparison withnullorboolconverts both sides to booleans, so[] == falseand"0" == falsearetrue.- Arrays.
==is true for the same key/value pairs;===also needs the same order and types.<=>compares count first, then values by key. - Objects.
==compares class and properties;===compares identity. See object comparison. - Floats. Never compare computed floats with
==; use a tolerance. - Chaining is not allowed for non-associative operators:
1 < 2 < 3is a syntax error. - Sorting.
<=>is the ideal body of ausort()callback. Comparing arrays with<=>gives multi-key sorting for free. - Helper functions.
strcmp()andstrcasecmp()return negative, zero or positive;in_array($x, $list, true)for strict search.