2

I've been digging in and learning as much as I can about PHP Arrays, but have hit a stumbling block that I cannot figure out.

In my example code, I have an array that looks like this:

$array = array("fruit" => array("apple", "orange", "pear"), "veg" => array("carrot","celery"));

Now, elsewhere in the code, I have a variable called $myfavouriteitem

$myfavouriteitem = "apple";

With the value of the $myfavouriteitem variable, I'd like to return the value "fruit".

I've tried using array_search() function in PHP, but I'm not having luck. I was able to use array_search() until the point where I introduced the nested array.

If I'm approaching this from the wrong angle, please let me know. My initial thought on this was to use a database to store this information (especially since I'm new to arrays); however, that's out of the question for this particular project. With that in mind, my data sets will all have a one-to-many relationship (one key with multiple values).

2 Answers 2

1
foreach ($array as $key => $val) {
    if (in_array($myfavouriteitem, $val)) {
        echo $key;
        break;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Wonderful. Thanks, Zerkms. I was able to get this to work for me. I am going to spend some more time reviewing PHP arrays.
1
echo key(array_filter($array, function ($values) use ($myfavouriteitem) { return in_array($myfavouriteitem, $values); }));

Needs PHP 5.3 though and may be slower than @zerkms solution. But hey, it's a functional one-liner! ;)

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.