Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
377 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...