PHP loose comparison: == vs ===

The one-line trap

In PHP, == does type juggling before it compares. That sounds convenient — until it silently passes a check you expected to fail.

The classic surprise

var_dump(0 == "foo");      // bool(true)  ???
var_dump("foo" == 0);      // bool(true)
var_dump("15" == "0xF");   // bool(true)  (hex string parsed!)
var_dump("0" == "00");     // bool(true)
var_dump("123abc" == 123); // bool(true)

Why? When a non-numeric string is compared against a number, PHP casts the string to 0. "foo" isn’t numeric, so it becomes 0, and 0 == 0 is true. "15" and "0xF" both parse to the integer 15.

How this leaks into real code

$allowed = [0, 1, 2];            // numeric role ids
if (in_array($input, $allowed)) {  // loose by default
    grant_access();
}
// $input = "hacker"  →  "hacker" == 0  →  true  →  access granted

in_array() uses loose comparison unless you pass true as the third argument. The same applies to array_search().

switch is loose too

switch ($status) {
    case 0:       echo "ok";     break;
    case "active": echo "active"; break;
}
// $status = "active"  →  "active" == 0 is true  →  hits case 0 first!

The first case that loosely matches wins, and "active" == 0 is true — so your string falls into the numeric branch.

The fix: be strict, always

in_array($input, $allowed, true);   // strict — the only safe default
$input === 0;                       // never use ==
switch ($status) { /* keep every case the same type */ }

Good habit: when comparing against a known scalar, make both sides the same type. If one side is user input (always a string), cast it explicitly before comparing.

Cheat sheet

  • Use === / !== unless you explicitly want coercion.
  • in_array() / array_search() — always pass true.
  • switch cases are loose; keep case values one type.
  • Numeric strings are parsed as hex/decimal/scientific: "15" == "0xF" is true.
  • Compare strings with ===; reach for strcmp() only when you need ordering.

When loose comparison is actually fine

When both operands are already the same type — two ints straight from the database, for example — == is harmless. The danger lives only at type boundaries: user input, parsed JSON, and form data, which all arrive as strings.