Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Concepts and Reference

PHP loose comparison tables

PHP 8 loose comparison explained with generated tables: how == treats numbers, numeric strings, null, booleans and arrays, and when to use === instead.

PHP has two equality operators. === (identical) is true only when value and type match. == (loose equality) converts the operands first, which is convenient and sometimes surprising. PHP 8 changed one important rule: when a number is compared with a non-numeric string, the number is converted to a string, instead of the string becoming 0.

This page builds the tables by running the comparisons, so every cell is real output from PHP 8.5.

PHP
<?php
var_dump(0 == "a");     // false in PHP 8 (true in PHP 7)
var_dump("1" == "01");  // true: both numeric strings
var_dump(null == false); // true

Try it

PHP A loose comparison table

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 Numeric strings, spaceship and strict comparison

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 rules

How == decides, in order (simplified):

Operands Rule
null or bool with anything Both sides convert to bool. So null == false, "0" == false, [] == false.
Two numeric strings Compared as numbers: "10" == "1e1".
Number and numeric string Compared as numbers. Leading whitespace is allowed, and since PHP 8 trailing whitespace is too.
Number and non-numeric string The number becomes a string, then they compare as strings: 0 == "a" is false.
null and string null becomes "": null == "" is true.
Two arrays Equal if they have the same key/value pairs (==), or also the same order and types (===).
Two objects Same class and equal properties for ==; the same instance for ===.

<=> uses the same conversions and returns -1, 0 or 1.

Usage notes

  • Default to === and !==. Use == only when you know both sides are the same kind of value.
  • switch uses loose comparison; match uses strict comparison.
  • in_array() and array_search() are loose unless you pass true as the third argument.
  • Sorting mixed types (sort() with default flags) uses these rules too, which can give inconsistent orders. Use a comparison callback or SORT_STRING.
  • A string like "0e123" is numeric (scientific notation), so two different-looking "hashes" starting with 0e followed by digits compare equal with ==. Compare hashes with hash_equals().
  • NAN is never equal to anything, including itself.
  • Comparing "abc" with 0 was true before PHP 8.0, so old code may behave differently now.