Comparing different strings in PHP with == returns true

寵の児 提交于 2019-12-04 14:15:14
Hanky Panky
<?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

Áxel Costas Pena

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.

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