简体   繁体   English

如何将字符串与零进行比较才是正确的?

[英]How can comparing string to zero be true?

php -a
Interactive shell

php > var_dump("some" == 0);
bool(true)
php > var_dump("some" == false);
bool(false)
php > var_dump("some" == true);
bool(true)
php > var_dump(false == 0);
bool(true)

My question is simple. 我的问题很简单。 What is the reasoning behind ("some" == 0) === true ? ("some" == 0) === true背后的原因是什么? I understand that due to the weak typing the operands are converted to something comparable. 我知道由于输入类型较弱,操作数会转换为可比较的值。 But in this particular example it's against how I understand it. 但是在这个特定示例中,这与我的理解背道而驰。

If the zero would be converted to string it would be: 如果零将转换为字符串,则将是:

php > var_dump("some" == "0");
bool(false)

If it was converted to bool, it would be: 如果将其转换为bool,则可能是:

php > var_dump("some" == false);
bool(false)

Only sensible explanation is: 唯一明智的解释是:

php > var_dump(intval("some"));
int(0)
php > var_dump(intval("some") == 0);
bool(true)

But that's certainly not what I or anyone would expect. 但这当然不是我或任何人所期望的。 Especially because any string would be turned to zero (and that potentially means false in any comparison). 尤其是因为任何字符串都将变为零 (并且在任何比较中都可能意味着错误)。

Why is it this way? 为什么这样呢?

Update: 更新:

My question was more about "why" not "if" or "how", sorry if that was not quite obvious. 我的问题更多是关于“为什么”而不是“如果”或“如何”,对不起,如果不是很明显的话。 And I think I found my answer in Why PHP casts two numerical strings to numbers before [loosely] comparing them? 而且我想我的答案出在为什么PHP在[松散地]比较它们之前将两个数字字符串转换为数字?

Simples 简单的

php > var_dump("some" == 0);

The string "some" is cast to an integer for comparison with an integer, and will be cast to a 0 in this case. 字符串“ some”被强制转换为整数以便与整数进行比较,在这种情况下将被强制转换为0

0 == 0 is true 0 == 0为真

If the string "13 monkeys" was cast to an integer, it would be a value of 13 如果将字符串“ 13 Monkeys”强制转换为整数,则其值为13

php > var_dump("13monkeys" == 0);

13 == 0 is false 13 == 0为假

The rules for casting a string to a number are explained in the PHP docs PHP文档中说明了将字符串强制转换为数字的规则

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM