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?'; } 

Result: hey is obviously in an array?

This makes no sense to me, please explain why. And how to fix it?

+7
source share
2 answers

This is because true == 'hey' because of the juggling type . What are you looking for:

 if (in_array($input, $arr['test'], true)) { 

It produces an equality test based on === instead of == .

 in_array('hey', array('soap' => true)); // true in_array('hey', array('soap' => true), true); // false 

To understand type juggling better, you can play with this:

 var_dump(true == 'hey'); // true (because 'hey' evaluates to true) var_dump(true === 'hey'); // false (because strings and booleans are different type) 

Update

If you want to find out if the <array> array (and not the value) is set, you should use isset() :

 if (isset($arr['test'][$input])) { // array key $input is present in $arr['test'] // ie $arr['test']['hey'] is present } 

Update 2

There is also array_key_exists() , which can check for the presence of an array key; however, it should be used only if it is likely that the corresponding array value may be null .

 if (array_key_exists($input, $arr['test'])) { } 
+11
source

You use an array as a dictionary, but the in_array function should be used when you use it as an array. Check the documentation .

+2
source

All Articles