0

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?

1 Answer 1

4

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";
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.