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 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
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.
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. switchuses loose comparison;matchuses strict comparison.in_array()andarray_search()are loose unless you passtrueas the third argument.- Sorting mixed types (
sort()with default flags) uses these rules too, which can give inconsistent orders. Use a comparison callback orSORT_STRING. - A string like
"0e123"is numeric (scientific notation), so two different-looking "hashes" starting with0efollowed by digits compare equal with==. Compare hashes withhash_equals(). NANis never equal to anything, including itself.- Comparing
"abc"with0wastruebefore PHP 8.0, so old code may behave differently now.