$arr = array(
'test' => array(
'soap' => true,
),
);
$input = 'hey';
if (in_array($input, $arr['test'])) {
echo $input . ' is apparently in the array?';
}
结果: 嘿显然是在阵列?in_array没有任何意义
这对我没有任何意义,请解释原因。我该如何解决这个问题?
$arr = array(
'test' => array(
'soap' => true,
),
);
$input = 'hey';
if (in_array($input, $arr['test'])) {
echo $input . ' is apparently in the array?';
}
结果: 嘿显然是在阵列?in_array没有任何意义
这对我没有任何意义,请解释原因。我该如何解决这个问题?
那是因为true == 'hey'
归因于type juggling。什么你要找的是:
if (in_array($input, $arr['test'], true)) {
它迫使基于===
而不是==
一个平等的测试。
in_array('hey', array('soap' => true)); // true
in_array('hey', array('soap' => true), true); // false
要理解型杂耍更好的你可以这样玩:
var_dump(true == 'hey'); // true (because 'hey' evaluates to true)
var_dump(true === 'hey'); // false (because strings and booleans are different type)
更新
如果你想知道一个数组键设置(而不是如果值是存在的),您应该使用这样的isset()
:
if (isset($arr['test'][$input])) {
// array key $input is present in $arr['test']
// i.e. $arr['test']['hey'] is present
}
更新2
还有array_key_exists()
可测试数组的键存在;但是,只有在相应的数组值可能为null
的可能性时才应该使用它。
if (array_key_exists($input, $arr['test'])) {
}
您正在使用该数组作为字典,但当您使用它作为数组时,将使用in_array
函数。检查the documentation。
啊,我明白了。它也在查看每个数组键的值。 – John
@John它实际上**只是**看着这些。 – ComFreek
@John我已经更新了答案,以防你正在寻找别的东西。 –