PHP 函数 in_array(...) 有什么问题?
What is wrong with the PHP function in_array(...)?
PHP函数in_array(...)
"checks if a value exists in an array".
但我在处理字符串时观察到一个非常奇怪的行为 (PHP v7.0.3
)。此代码
$needle = 'a';
$haystacks = [['a'], ['b'], [123], [0]];
foreach ($haystacks as $haystack) {
$needleIsInHaystack = in_array($needle, $haystack);
var_dump($needleIsInHaystack);
}
生成以下输出:
bool(true)
bool(false)
bool(false)
bool(true) <- WHAT?
函数 returns true
用于每个 string
$needle
,如果 $haystack
包含一个值为 0
的元素!
真的是设计出来的吗?还是应该报告的错误?
如果不将in_array
的第三个参数设置为true,则使用类型强制进行比较。
If the third parameter strict is set to TRUE then the in_array() function will also check the types of the needle in the haystack.
在 loose comparison rules 下,实际上 'a'
等于 0
因为 (int)'a' == 0
.
PHP函数in_array(...)
"checks if a value exists in an array".
但我在处理字符串时观察到一个非常奇怪的行为 (PHP v7.0.3
)。此代码
$needle = 'a';
$haystacks = [['a'], ['b'], [123], [0]];
foreach ($haystacks as $haystack) {
$needleIsInHaystack = in_array($needle, $haystack);
var_dump($needleIsInHaystack);
}
生成以下输出:
bool(true)
bool(false)
bool(false)
bool(true) <- WHAT?
函数 returns true
用于每个 string
$needle
,如果 $haystack
包含一个值为 0
的元素!
真的是设计出来的吗?还是应该报告的错误?
如果不将in_array
的第三个参数设置为true,则使用类型强制进行比较。
If the third parameter strict is set to TRUE then the in_array() function will also check the types of the needle in the haystack.
在 loose comparison rules 下,实际上 'a'
等于 0
因为 (int)'a' == 0
.