Avatar ·

Difference between == and === in PHP

Difference between == and === in PHP: strange behavior when comparing string and number

Hello everyone! I'm a beginner in PHP and encountered unexpected behavior of comparison operators. I'm trying to understand the difference between == (loose equality) and === (strict equality).

I have a simple code:

$a = '123abc';\n$b = 123;\n\nvar_dump($a == $b);  // Result: true\nvar_dump($a === $b); // Result: false

I expected both comparisons to return false because the types are different (string and number). But == returns true. Why does this happen? I read that == performs type coercion, but I don't understand how the string '123abc' can be equal to the number 123.

What I have already tried:

  • Checked with different strings (e.g., 'abc123' — there == returned false)
  • Read the PHP documentation on operators