Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

in_array() on multidimensional array

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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";
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading