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 7true, PHP 8false'1' == '01'stilltrue(both numeric)- Affects
switch,in_arrayandarray_searchwithout 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
- What are the most important features introduced in PHP 8.0?
- What happens to an HTTP request in a PHP-FPM application, and what does 'shared nothing' mean?
- How should passwords be stored in PHP?
- What are named arguments and what are their benefits and risks?
- What is constructor property promotion?
- How does `match` differ from `switch`?
- What are union types in PHP 8 and how do you use them?
- What are enums in PHP 8.1? Explain pure vs backed enums.