Empty string comparison to zero gives different result in PHP 8 than in previous versions

You are right, this is a major change.

As with any version upgrade, you can find a guide to Migrating to PHP 8.0 in the official PHP manual. If you click on Backward Incompatible Changes you will see that this change is the very first thing on that page:

Non-strict comparisons between numbers and non-numeric strings now work by casting the number to string and comparing the strings.

As well as an example in the next sentence, there is a before-and-after comparison table which includes the exact example you gave:

Comparison: 0 == ""; Before: true; After: false

If you have code that was relying on the old behaviour, you will need to update it to be more explicit about the values expected. For instance, all of the following work in all versions of PHP:

if ( $value === 0 || $value === "" ) { ... }
if ( (string)$zero === "" ) { ... }
if ( (int)$emptyString === 0 ) { ... }

For more background on the change, you can read the original proposal here: PHP RFC: Saner string to number comparisons

Leave a Comment