Why is integer 0 equal to a string in PHP? [duplicate]

只谈情不闲聊 提交于 2019-12-20 02:36:16

问题


Possible Duplicate:
How do the equality (== double equals) and identity (=== triple equals) comparison operators differ?

Why this

var_dump(0 == "string");

outputs this

bool(true)

Isn't the context of == operator supposed to convert 0 into FALSE and "string" into TRUE according to this set of rules?


回答1:


var_dump(0 == "string");

is doing a numeric (integer) comparison

0 is an integer, so "string" is converted to an integer to do the comparison, and equates to an integer value of 0, so 0 == 0 is true

Se the comparison with various types table in the PHP documentation for details




回答2:


The table shown here is more fit for your case.

It shows TRUE for comparing 0 with "php".

Within the comparison you do not convert both operands to a boolean, but one operand will be converted to match the type of the other operand. In your case the string gets converted to an integer, which results in another 0. This gives you 0 == 0, which yields true.




回答3:


They are not of the same type, use === if you want to check if they are also of the same type.




回答4:


PHP: ==

If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically.

"string" is not number format, so it will be convert to 0.




回答5:


during the comparison, the string is converted to an integer:

var_dump(0);
var_dump((int)"string");
var_dump(0 == "string");

last line will be automatically converted to:

var_dump(0 == (int)"string");

so this return will return:

int(0)
int(0)
bool(true)
bool(true)



回答6:


You're looking for the comparison table on this site first: http://php.net/manual/en/language.operators.comparison.php. Casting to bool doesn't apply here.

Operand 1           Operand 2
...
string, resource    string, resource    Translate strings and resources to numbers,
or number           or number           usual math

"string" cast to a number equals 0.



来源:https://stackoverflow.com/questions/13970544/why-is-integer-0-equal-to-a-string-in-php

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