为什么 (0 == 'Hello') 在 PHP 中返回 true? [英] Why does (0 == 'Hello') return true in PHP?
问题描述
嘿,如果您有以下代码并想检查 $key
是否匹配 Hello
我发现,比较总是返回 true
如果变量是 0
.当一个特殊键的数组时,我遇到了这个问题,并想知道为什么它没有按预期工作.有关示例,请参阅此代码.
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
谁能解释一下?
推荐答案
运算符 ==
和 !=
不比较类型.因此 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屋!