[英]in_array doesn't make any sense
$arr = array(
'test' => array(
'soap' => true,
),
);
$input = 'hey';
if (in_array($input, $arr['test'])) {
echo $input . ' is apparently in the array?';
}
结果:嘿显然在阵列中?
这对我没有任何意义,请解释原因。 我该如何解决这个问题?
这是因为true == 'hey'
由于类型杂耍 。 你在寻找的是:
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
函数。 查看文档 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.