Skip to main content

How to Compare Values in PHP with === (Strict Comparison)

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

PHP has two equality operators. == converts the values to a common type before comparing them, which sometimes calls different things equal. === compares the value and the type, so it's only true when both match exactly.

Syntax​

Syntax
$<a> === $<b>
$<a> !== $<b>
PartWhat it does
===true when both sides have the same value and the same type.
!==true when the value or the type differs.
==true when the values are equal after PHP converts them, "type juggling".

The PHP manual on comparison operators defines $a === $b as "true if $a is equal to $b, and they are of the same type", and $a == $b as "true if $a is equal to $b after type juggling."

The Example​

The example compares three pairs of values twice, once with == and once with ===, and prints each result with var_dump.

Prerequisites​

  • PHP for the command line. This guide uses PHP 8.6.0.

Step 1: Write the Comparisons​

Create a file named main.php:

main.php, which var_dumps 0 == '0', 0 === '0', '1e3' == '1000', '1e3' === '1000', null == false and null === false.

main.php
<?php

var_dump(0 == '0');
var_dump(0 === '0');
var_dump('1e3' == '1000');
var_dump('1e3' === '1000');
var_dump(null == false);
var_dump(null === false);

Step 2: Run It​

Terminal
php main.php
Output
bool(true)
bool(false)
bool(true)
bool(false)
bool(true)
bool(false)

A zsh terminal where php main.php prints bool(true) and bool(false) three times in turn.

  • 0 == '0' is true: the string is converted to a number. With ===, an int and a string differ.
  • '1e3' == '1000' is true: both strings look like numbers, so PHP compares them as numbers, and 1e3 is 1000.
  • null == false is true, but null and false are different types.

The command is the same in zsh, bash and PowerShell.

Common Mistakes​

MistakeWhat happensDo this instead
Comparing user input with ==Different strings such as '1e3' and '1000' count as equalUse ===
Testing a function's result with == false0, '' and '0' also matchCompare with === false
Expecting old PHP 7 resultsPHP 8 compares a number with a non-numeric string as strings, so 0 == 'a' is falseDon't rely on == between numbers and text

Troubleshooting​

SymptomLikely causeFix
Two different-looking values compare as equal== converted themSwitch to ===
A check fails although the values look the sameOne is an int, the other a stringConvert one side, or compare with == on purpose

FAQ​

Is there a strict "not equal"?​

Yes: !== is true when the value or the type differs.

Does === compare arrays?​

Yes: two arrays are identical when they have the same key and value pairs, in the same order and of the same types.

Conclusion​

=== compares the value and the type, so it never converts anything; == converts first and can call different values equal. Use === by default.

Additional Resources​