What is the difference between == and === in PHP?

What is the difference between == and === in PHP?

What is the difference between == and === in PHP?

Question

What is the difference between == and === in PHP?

Answer

== is a loose comparison. PHP coerces (converts) the types of both operands before comparing, which can produce unexpected results:

0   == "foo"   // true  ⚠️  ("foo" cast to int = 0)
0   == ""      // true  ⚠️
0   == "0"     // true
1   == "1"     // true
100 == "1e2"   // true  (scientific notation)
""  == false   // true
""  == null    // true
0   == null    // true
"1" == "01"    // true

=== is a strict comparison. Both value AND type must match — no coercion occurs:

0   === "foo"  // false ✅
0   === 0      // true
1   === "1"    // false ✅ (int vs string)
""  === false  // false ✅
null === false // false ✅
"1" === "1"   // true

Best Practice

Always use === (and !==) unless you specifically need type coercion. This prevents entire classes of bugs, especially when comparing values that might be 0, "", null, or false.

// Dangerous — returns user with id 0 if $id is "foo"
$user = array_search($id, $ids);

// Safe
$user = array_search($id, $ids, strict: true);
All Comments