Skip to content

PHP 8: Saner string to number comparisons

Comparisons between strings and numbers using == and other non-strict comparison operators currently work by casting the string to a number and subsequently performing a comparison on integers or floats. This results in many surprising comparison results, the most notable of which is that 0 == "foobar" returns true.  PHP 8 fixed this issue using number comparison when comparing to a numeric string. Otherwise, it converts the number to a string and uses a string comparison.

Comparison    | Before | PHP 8
------------------------------
 0 == "0"     | true   | true
 0 == "0.0"   | true   | true
 0 == "foo"   | true   | false
 0 == ""      | true   | false
42 == "   42" | true   | true
42 == "42foo" | true   | false
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments