Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in_array doesn't make any sense

Tags:

php

$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?

like image 798
John Avatar asked Dec 16 '12 12:12

John


2 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'])) {
}
like image 151
Ja͢ck Avatar answered Nov 05 '22 01:11

Ja͢ck


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.

like image 31
Noufal Ibrahim Avatar answered Nov 04 '22 23:11

Noufal Ibrahim