简体   繁体   English

为什么“1 | 2”== 1在PHP中返回true?

[英]Why does “1|2” == 1 return true in PHP?

Why does this code return True instead of False? 为什么这段代码返回True而不是False?

"1|2" == 1

why doesn't it return False? 为什么不返回False?

attention : 1|2 is string. 注意:1 | 2是字符串。

Your string "1|2" is cast to an integer for the comparison with integer 1. 您的字符串"1|2"将转换为整数,以便与整数1进行比较。

According to PHP's type casting rules , casting strings to integers takes all leading digits from the string up to the first non-digit (giving 1 , and ignoring |2 because | is the first non-digit. 根据PHP的类型转换规则 ,将字符串转换为整数会将字符串中的所有前导数字转换为第一个非数字(给出1 ,忽略|2因为|是第一个非数字。

1 == 1 is true 1 == 1是真的

When converted into a number "1|2" becomes 1 as the cast processes the string until the first non-numerical character. 转换为数字时, "1|2"变为1因为转换处理字符串直到第一个非数字字符。 1 == 1 so this is true. 1 == 1所以这是真的。 Strings are converted into numbers during == comparisons ==比较期间,字符串将转换为数字

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. 如果将数字与字符串进行比较或比较涉及数字字符串,则每个字符串将转换为数字,并且数字执行比较。

http://php.net/manual/en/language.operators.comparison.php http://php.net/manual/en/language.operators.comparison.php

If you want to fix it use the === operator which will also check types 如果你想修复它,使用===运算符,它也会检查类型

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

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