2012-12-16 81 views
7
$arr = array(
    'test' => array(
     'soap' => true, 
    ), 
); 

$input = 'hey'; 
if (in_array($input, $arr['test'])) { 
    echo $input . ' is apparently in the array?'; 
} 

结果: 嘿显然是在阵列?in_array没有任何意义

这对我没有任何意义,请解释原因。我该如何解决这个问题?

回答

11

那是因为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'])) { 
} 
+0

啊,我明白了。它也在查看每个数组键的值。 – John

+0

@John它实际上**只是**看着这些。 – ComFreek

+0

@John我已经更新了答案,以防你正在寻找别的东西。 –

2

您正在使用该数组作为字典,但当您使用它作为数组时,将使用in_array函数。检查the documentation

+0

所以你说我错过了数组,请ellobarate如果有更聪明的方法做什么即时通讯试图实现。 – John

+0

@John'in_array()'搜索一个值。所以它通过每个项目,并检查针对。但是如果你不使用严格模式,'true =='hey''将被评为TRUE。看到我对杰克答案的编辑。 – ComFreek