PHP 8 interview question · Most asked

How did string-to-number comparison change in PHP 8?

Summary

When comparing a number with a non-numeric string, PHP 8 now compares them as strings instead of casting the string to a number, so 0 == 'foo' is false (it was true in PHP 7).

Longer Answer

PHP 7 cast 'foo' to 0, making 0 == 'foo' true, a classic source of security bugs (e.g. in loose in_array or switch). PHP 8's "Saner string to number comparisons" RFC: if the string is numeric, compare as numbers; otherwise cast the number to a string and compare strings.

Also, PHP 8 treats leading-numeric strings like '42abc' more consistently ("Saner numeric strings" RFC): arithmetic on them gives a warning instead of a notice, and non-numeric strings in arithmetic throw TypeError.

Key Points

  • 0 == 'foo': PHP 7 true, PHP 8 false
  • '1' == '01' still true (both numeric)
  • Affects switch, in_array and array_search without strict mode
  • Prefer === and strict flags anyway

Comparison / Tradeoffs

Expression PHP 7 PHP 8
0 == 'foo' true false
'1' == '01' true true
100 == '1e2' true true
null == false true true

Explanation

Common mistakes

  • Relying on loose comparison for auth/permission checks

More most-asked PHP 8 questions

← All PHP 8 questions