PHP:字符串真正的回报比较奇怪的结果
问题描述:
我将不胜感激,如果有人可以给我解释为什么下面的代码...PHP:字符串真正的回报比较奇怪的结果
$result = true;
if ($result == "discontinued"){
echo "IN";
}
if ($result == "invalid"){
echo "IN2";
}
同时触发回声(即ININ2。)......我知道我可以将操作符更改为===,它可以工作,但我不明白发生了什么。谢谢
答
当使用比较(==
)运算符时,任何无法转换为false的值都将计为true。这包括任何非空字符串。这是因为type juggling in PHP。所以"discontinued"
评估为真,因为它不是一个空字符串。如果使用相同的运算符(===
),则类型转换没有完成,因此"discontinued"
被视为文字字符串,然后您的语句将计算为false。
当执行类型杂耍时,以下将评估为错误。其他将被评估为真:
- “”(空字符串)
- 0(0作为整数)
- 0.0(0为float)
- “0”(0作为字符串)
- NULL
- FALSE
- 阵列()(空数组)
- $变种; (一个变量声明,但没有值)
因为[this](http://php.net/manual/en/types.comparisons.php)和[this](http:// php。 net/manual/zh/language.types.type-juggling.php) –
http://www.php.net/manual/en/types.comparisons.php –
哈哈老式的杂耍xD ... btw。有[strval](http://php.net/manual/en/function.strval.php)从(铸造)字符串中获取值,也适用于将对象转换为字符串。 – timwebdev