Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
389 views
in Technique[技术] by (71.8m points)

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

This code gives a different result in PHP 8 than in all previous versions of PHP:

if ('' == 0)
  echo 'PHP '.phpversion().' says yes';
else
  echo 'PHP '.phpversion().' says no';


PHP 7.2.12 says yes
PHP 7.4.14 says yes
PHP 8.0.0 says no

This seems like a major change. What is going on here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 ) { ... }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...