Home > other >  in_array() on multidimensional array
in_array() on multidimensional array

Time:01-15

I want to find an array inside an array by its value.

Example: It returns "Match not found", while "Peter" is inside the $people array. But I can found "Joe".

$people = array(
  "Peter" => array (
        "test" => 0
    ),
  "Joe"
);

if (in_array("Peter", $people))
  {
     echo "Match found";
  }
else
  {
     echo "Match not found";
  }

How can I found "Peter" in the array?

CodePudding user response:

Using in_array search for values, but in your code Peter is a key. Then you can use array_key_exists instead:

$people = array(
    "Peter" => array (
        "test" => 0
    ),
    "Joe"
);

if (array_key_exists("Peter", $people))
{
    echo "Match found";
}
else
{
    echo "Match not found";
}

Output

Match found

you can combine both since the name you're searching is sometimes the value like "Joe" in your example.

if (array_key_exists("Peter", $people) || in_array("Peter", $people)) {
    echo "Match found";
} else {
    echo "Match not found";
}

CodePudding user response:

in_array() does not work on multidimensional arrays. You could write a recursive function to do that for you:

function in_array_r($needle, $haystack, $strict = false) {
    foreach ($haystack as $item) {
        if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
            return true;
        }
    }

    return false;
}

Then

$people = array(
  "Peter" => array (
        "test" => 0
    ),
  "Joe"
);

echo in_array_r("Peter", $people) ? 'found' : 'not found';
  •  Tags:  
  • Related