我最近遇到一个奇怪的问题in_array,我无法理解.例如
$a = array('a','b','c');
$b = array(1,2,3);
if (in_array(0,$a))
{
echo "a bingo!\n";
}
else
{
echo "a miss!\n";
}
if (in_array(0,$b))
{
echo "b bingo!\n";
}
else
{
echo "b miss!\n";
}
Run Code Online (Sandbox Code Playgroud)
我把它放在我的灯上,然后得到了
a bingo!
b miss!
Run Code Online (Sandbox Code Playgroud)
我阅读了手册并将第三个参数设置$strict为true,然后按预期工作.但这是否意味着我总是需要在使用时将strict参数设置为true in_array?建议将不胜感激.
问候
关于PHP的in_array()帮助页面(http://uk.php.net/manual/en/function.in-array.php#106319)的最新评论指出,由于PHP"对变量类型的宽容",会出现一些不寻常的结果,但没有解释为什么会出现这些结果.特别是,我不遵循为什么会发生这种情况:
// Example array
$array = array(
'egg' => true,
'cheese' => false,
'hair' => 765,
'goblins' => null,
'ogres' => 'no ogres allowed in this array'
);
// Loose checking (this is the default, i.e. 3rd argument is false), return values are in comments
in_array(763, $array); // true
in_array('hhh', $array); // true
Run Code Online (Sandbox Code Playgroud)
或者为什么海报认为以下是奇怪的行为
in_array('egg', $array); // true
in_array(array(), $array); // true
Run Code Online (Sandbox Code Playgroud)
(当然'egg'确实出现在数组中,PHP并不关心它是一个键还是一个值,并且有一个数组,并且PHP不关心它是否为空?)
任何人都可以提供任何指示..?