Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 147 ยท Operators

Comparison Operators

Learn PHP comparison operators - == vs ===, != and !==, less and greater than, the spaceship operator, comparing strings and arrays, and the PHP 8 rules.

A comparison operator asks a question about two values ("are they equal?", "is this one smaller?") and answers with a boolean: true or false. Every if, every loop condition, every search and every sort in your programs relies on comparisons, so getting them right is one of the most important skills in PHP.

PHP has two kinds of equality. Loose comparison (==) converts the values to a common type before comparing, while strict comparison (===) requires the same type and the same value. Loose comparison is the source of some of PHP's most famous surprises. This lesson explains both, gives you a simple rule for choosing between them, covers ordering with <, > and the spaceship operator <=>, and shows how strings, arrays, null and objects compare.

You've already seen how PHP converts types in Type Juggling and Casting; this lesson applies those rules to comparisons. The booleans that comparisons produce are combined with &&, || and ! in the next lesson, Logical Operators.

The comparison operators

Operator Name True when
$a == $b Equal $a equals $b after type juggling
$a === $b Identical $a equals $b and they have the same type
$a != $b or $a <> $b Not equal not ==
$a !== $b Not identical not ===
$a < $b Less than $a is smaller
$a > $b Greater than $a is larger
$a <= $b Less than or equal $a is smaller or equal
$a >= $b Greater than or equal $a is larger or equal
$a <=> $b Spaceship returns -1, 0 or 1 (an int, not a bool)

== versus ===

The difference shows up as soon as the two sides have different types:

PHP Loose and strict equality

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.

The output pairs up neatly:

TEXT
bool(true)
bool(true)
bool(false)
bool(true)
bool(true)
bool(false)
bool(true)
bool(false)
bool(false)
bool(true)
bool(false)

5 == '5' converts the string to a number, so it's true; 5 === '5' compares an int with a string, so it's false without looking any further. 1.0 === 1 is false too: same mathematical value, different types. The string comparisons at the end show that == treats two numeric strings as numbers, so '1e3' == '1000' is true (both mean one thousand). Comparing strings with === checks them byte by byte, which is almost always what you mean.

Use === by default

The practical rule is simple: use === and !== unless you have a specific reason to want type juggling. Strict comparison is faster to reason about because there's nothing to look up, and it can't produce surprises like these:

PHP Why loose comparison is risky

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.

The first part shows why secrets and codes must be compared strictly (and, for secrets, in constant time with hash_equals(); see Password Hashing). The in_array() calls show the same issue inside a built-in function: in_array() and array_search() use == unless you pass true as the third argument, so '0.0' is "found" because it equals '0' numerically. Always pass true there. true == 'false' is true because any non-empty string other than '0' is truthy, while 0 == '' is false in PHP 8, as you'll see next.

The PHP 8 loose comparison table

When you do use ==, PHP picks a conversion based on the two types. These are the rules, in order:

  1. Both are strings that look like numbers ('10', ' 5', '1e3'): compared as numbers.
  2. A number and a string: if the string is numeric, compared as numbers; otherwise the number is converted to a string and they're compared as strings. (This is the PHP 8.0 change. Before, the string was always converted to a number, so 0 == 'abc' was true.)
  3. A bool or null on either side: both sides are converted to bool.
  4. Two arrays: equal if they have the same key/value pairs (see below).
  5. Anything else of different types: usually converted to numbers, though some combinations are simply never equal.

Here's how common values compare with == in PHP 8. T means true; a blank cell means false:

== true false 0 1 '' '0' 'a' null []
true T T T
false T T T T T T
0 T T T T
1 T T
'' T T T
'0' T T T
'a' T T
null T T T T T
[] T T T

You don't need to memorize this table; the point is that it exists, and that === replaces it with a single rule. Notice some oddities: null == 0 and null == '' are true, but 0 == '' is false; '0' == false is true but '0' == null is false. Loose equality isn't even transitive.

PHP Checking the table yourself

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.

The grid prints T where == is true and . where it's false. Change == to === on line 13 and run again: only the diagonal stays true.

Ordering: <, >, <= and >=

Numbers compare as you'd expect, and ints and floats mix freely (2 < 2.5 is true). Strings are where you need to pay attention:

  • Two numeric strings compare as numbers: '10' < '9' is false, because 10 is not less than 9.
  • Otherwise, strings compare byte by byte, like a dictionary, but by byte value. All uppercase ASCII letters come before all lowercase ones, so 'Z' < 'a' is true.
  • As soon as one string isn't numeric, the comparison is textual: '10' < '9a' is true, because the character 1 comes before 9.
PHP Comparing strings

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.

When you need precise control, use comparison functions instead of operators. They always compare as text and return a negative number, zero or a positive number:

Function Compares
strcmp($a, $b) Byte by byte, case-sensitive
strcasecmp($a, $b) Ignoring ASCII case
strnatcmp($a, $b) "Natural" order: img2 before img10
strnatcasecmp($a, $b) Natural order, ignoring case

None of these understand language rules like accents (รฉ sorts after z byte-wise). Locale-aware comparison needs the intl extension's Collator class, which isn't installed on our server. Sorting with these functions is covered in Sorting Arrays.

Comparison operators are non-associative: you can't chain them. 1 < $x < 10 is a parse error in PHP, unlike in Python. Write $x > 1 && $x < 10 instead, using the logical operators from the next lesson.

The spaceship operator <=>

The spaceship operator <=> (PHP 7.0+) compares two values and returns an int: -1 if the left side is smaller, 0 if they're equal, and 1 if the left side is larger. It uses the same rules as <, == and >. Its main job is sorting: usort() wants a callback that returns exactly that kind of number.

PHP Sorting with the spaceship operator

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.

To sort in descending order, swap the operands ($b <=> $a). The output lists Pen, Mug, Lamp, Desk, then the reverse, then Desk, Lamp, Mug, Pen. Comparing arrays with <=> compares them element by element, which gives you multi-key sorting for free: [$a['last'], $a['first']] <=> [$b['last'], $b['first']] sorts by last name, then first name. More in Sorting Arrays.

Comparing arrays

Arrays have their own equality rules:

  • $a == $b is true if both arrays have the same key/value pairs, compared loosely. Order doesn't matter.
  • $a === $b is true only if they have the same key/value pairs in the same order and with the same types.
PHP Array equality

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.

['red', 'blue'] == ['blue', 'red'] is false, which surprises people: list arrays have keys 0 and 1, so these arrays pair 0 => 'red' with 0 => 'blue'. If you want "same elements in any order", sort both first or compare with array_diff(). The last line shows how arrays are ordered: an array with fewer elements is smaller, whatever the values, so [1, 2, 3] > [9, 9] is true. Arrays with the same count compare element by element.

Comparing objects and null

Objects compare by identity with ===: two variables are identical only if they refer to the very same object. With ==, two objects are equal if they're instances of the same class with equal properties:

PHP
$a = new stdClass();
$a->x = 1;
$b = new stdClass();
$b->x = 1;
$c = $a;

var_dump($a == $b);   // bool(true): same class, same properties
var_dump($a === $b);  // bool(false): two different objects
var_dump($a === $c);  // bool(true): the same object

Comparing, Copying and Serializing Objects goes deeper. For null, always use === null (or is_null()): null == 0, null == '', null == false and null == [] are all true, and null < -1 is even true, because both sides become booleans (false < true).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does var_dump('100' == '1e2'); print?

    Both strings are numeric, so == compares them as numbers, and 1e2 is 100. With === the result would be false.
  2. 2. What does var_dump('10' < '9'); print?

    Two numeric strings are compared as numbers, and 10 is not less than 9. Comparing '10' with '9a' would be textual and return true.
  3. 3. What does 5 <=> 3 evaluate to?

    The spaceship operator returns 1 when the left side is greater, 0 when equal and -1 when smaller.
  4. 4. Why should you write in_array($value, $list, true)?

    in_array and array_search compare with == by default. Passing true switches them to ===.
  5. 5. $a = [0 => 'x', 1 => 'y']; and $b = [1 => 'y', 0 => 'x']; Which is true?

    Both arrays have the same key/value pairs, so they're loosely equal. They're not identical because the pairs are in a different order.

Summary

  • == compares after type juggling; === requires the same type and value. Use === and !== by default, and pass true to in_array() and array_search().
  • In PHP 8, a number and a non-numeric string compare as strings, so 0 == 'abc' is false. Two numeric strings still compare as numbers ('1e3' == '1000').
  • Strings order byte by byte (uppercase before lowercase); use strcmp, strcasecmp and strnatcmp for explicit text comparison.
  • Comparisons can't be chained: write $x > 1 && $x < 10.
  • <=> returns -1, 0 or 1 and is the standard way to write usort() callbacks; swap operands for descending order.
  • Arrays are == with the same key/value pairs in any order, and === only in the same order with the same types. A shorter array is always smaller.
  • Objects are === only when they're the same instance. Test null with === null.

Next: Logical Operators