PHP 代码:
<?php
$key = 0;
if($key == 'monty' && $key == 'anil'){
echo 'Mackraja';
}else{
echo "Nothing";
}
?>
或
<?php
$key = 2;
if($key == '2abc' || $key == 'abc2'){
echo 'Mackraja';
}else{
echo "Nothing";
}
?>
输出:Mackraja
最佳答案
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. These rules also apply to the switch statement. - Source
这意味着
<?php
var_dump(0 == "a"); // 0 == 0 -> true
var_dump("1" == "01"); // 1 == 1 -> true
var_dump("10" == "1e1"); // 10 == 10 -> true
var_dump(100 == "1e2"); // 100 == 100 -> true
因此,当您比较 $key
时(值为 0
)到字符串,字符串的值为 0
并且它们都返回 true。这样,它将始终输出“Mackraja”。
更改 $key
的值任何其他整数将返回 false。
注意
The type conversion does not take place when the comparison is
===
or!==
as this involves comparing the type as well as the value. - Source
这意味着将比较运算符更改为 ===
将意味着值必须完全匹配 - 即字符串 1
将不等于整数 1:它们必须匹配格式:
echo $key == 'monty' && $key == 'anil' ? 'Mackraja' : 'Nothing';
//will echo "Mackraja"
echo $key === 'monty' && $key === 'anil' ? 'Mackraja' : 'Nothing';
//will echo "Nothing"
关于php - 在 IF 条件下与 int 和 string 进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35173422/