我无法理解为什么声明在两次都成真.$hello=foo;if($hello=6){echoyes\n; 我无法理解为什么声明在两次都成真. $hello="foo"; if($hello =0) { echo "ohh yess!"; } 它输出 yesohh yess! 我知道这是整数和字符串之
我无法理解为什么声明在两次都成真.
$hello="foo"; if($hello<=6){ echo "yes\n"; } if ($hello>=0) { echo "ohh yess!"; }
它输出
yesohh yess!
我知道这是整数和字符串之间的非法比较,但为什么它毕竟是真的.
解决方法:
正如PHP manual所说:
The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero).
在这种情况下,字符串foo在完成比较时评估为零,因此if条件将评估为TRUE.
实际上,你会做:
if(0 <= 6) { echo "yes\n";}if (0 >= 0) { echo "ohh yess!";}
如果要确保也考虑变量类型,请使用===运算符.