Home » Php » php – in_array doesn't make any sense

php – in_array doesn't make any sense

Posted by: admin July 12, 2020 Leave a comment

Questions:
$arr = array(
    'test' => array(
        'soap' => true,
    ),
);

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

Result:
hey is apparently in the array?

It doesn’t make any sense to me, please explain why. And how do I fix this?

How to&Answers:

That’s because true == 'hey' due to type juggling. What you’re looking for is:

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

It forces 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 know if an array key is set (rather than if a value is present), you should use isset() like this:

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

Update 2

There’s also array_key_exists() that can test for array key presence; however, it should only be used if there’s a possibility that the corresponding array value can be null.

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

Answer:

You’re using the array as a dictionary but the in_array function is to be used when you’re using it like an array. Check the documentation.