Skip to content
Tutorials Center
My learning

Topics

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.

PHP
var_dump(5 == "5");    // true
var_dump(5 === "5");   // false
echo 1 <=> 2;          // -1

Try it

PHP Loose versus strict

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.

PHP Spaceship and sorting

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

PHP
$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" is false in PHP 8 (it was true before). Two numeric strings are compared as numbers: "10" == "1e1" is true.
  • null and booleans. Loose comparison with null or bool converts both sides to booleans, so [] == false and "0" == false are true.
  • 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 < 3 is a syntax error.
  • Sorting. <=> is the ideal body of a usort() callback. Comparing arrays with <=> gives multi-key sorting for free.
  • Helper functions. strcmp() and strcasecmp() return negative, zero or positive; in_array($x, $list, true) for strict search.