为什么(0 =='Hello')在PHP中返回true? [英] Why does (0 == 'Hello') return true in PHP?
问题描述
嘿,如果您有以下代码并想检查 $ key
是否匹配 Hello
我是发现,如果变量是 0
,则比较总是返回 true
。我遇到了一个特殊键的数组,并想知道为什么它没有按预期工作。
请参阅此代码以获取示例。
Hey, if you have got the following code and want to check if $key
matches Hello
I've found out, that the comparison always returns true
if the variable is 0
. I've came across this when an array for a special key and wondered why it's wasn't working as expected.
See this code for an example.
$key = 1;
if ($key != 'Hello') echo 'Hello'; //echoes hello
$key = 2;
if ($key != 'Hello') echo 'Hello'; //echoes hello
$key = 0;
if ($key != 'Hello') echo '0Hello'; //doesnt echo hello. why?
if ($key !== 'Hello') echo 'Hello'; //echoes hello
任何人都能解释一下吗?
Can anyone explain this?
推荐答案
运营商 ==
和!=
不要比较类型。因此,PHP会自动将Hello转换为 0
( intval('Hello')
)的整数。如果不确定类型,请使用类型比较运算符 ===
和!==
。或者更好地确定您在程序中的任何一点处理哪种类型。
The operators ==
and !=
do not compare the type. Therefore PHP automatically converts 'Hello' to an integer which is 0
(intval('Hello')
). When not sure about the type, use the type-comparing operators ===
and !==
. Or better be sure which type you handle at any point in your program.
这篇关于为什么(0 =='Hello')在PHP中返回true?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!