Comparing different strings in PHP with == returns true

耗尽温柔 提交于 2020-01-13 05:16:06

问题


I was just debugging a script and found that an if-statement wasn't working the way I expected it to.

var_dump("6064365413078728979" == "6064365413078728452");
die();

The code above will result in the following:

bool(true)

With the === operator it works as expected. Anyone got any ideas why?

I'm using PHP Version 5.3.13 with a wamp installation on a x64 windows machine.


回答1:


<?php
$a=6064365413078728979;
$b=6064365413078728452;
echo $a."<br>".$b;
//var_dump( $a==$b );
die();
?>

When you run that, then on your machine that might be exceeding limit for a number and that is a numeric comparison taking place. Try the script above and see value for $a will probably be different than the value you gave.

That is why when both are compared numerically they are equal. Hence use === as suggested by others

Edit: Explanation based upon @Axel's Advice.

PHP Manual explains

The size of a float is platform-dependent, although a maximum of ~1.8e308 with a precision of roughly 14 decimal digits is a common value (the 64 bit IEEE format).

And this website is offering and explanation on the Overflow phenomenon and a small php code to test your system's integer and float range. Getting to know the limit on your servers will most probably explain it best why the offerflow occured




回答2:


PHP has loose type comparison behavior, so your numerical strings are getting converted to integer types before == non strict comparison, and the conversion result is overflowing.

That is the principal reason to use === when it's possible.

Take a look at this page for further details on type juggling.



来源:https://stackoverflow.com/questions/14259162/comparing-different-strings-in-php-with-returns-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!