php long numbers in string comparison

徘徊边缘 提交于 2019-12-11 10:39:18

问题


var_dump("555555555555555555555" == "555555555555555555553"); //bool(true)
var_dump("aaaaaaaaaaaaaaaaaaaaa" == "aaaaaaaaaaaaaaaaaaaab"); //bool(false)

Why does this happen?

I know I can use

var_dump(strcmp("555555555555555555555", "555555555555555555553") == 0); //bool(false)

But why the first row returns true?


回答1:


It's a side effect of type-coercing. There's an article on phpsadness about it. Basically, the strings in the comparison are converted to numeric types, and due to precision loss, appear to be equal.




回答2:


In your first row

var_dump("555555555555555555555" == "555555555555555555553");

it is true

Why because, the type-coercing comparison operators will coerce both operands to floats if they both look like numbers, even if they are both already strings

This bug is discussed here



来源:https://stackoverflow.com/questions/19161722/php-long-numbers-in-string-comparison

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