2

Is there any predefined PHP function to find a key in a multi dimensional array?

In the below example - there is a variable name 'rose' and I need to get the key of the array by using the variable name. The result of the key is "flower".

$array = array (
                    'fruits' => array (
                                            'mango',
                                            'cherry'
                                    ),
                    'flowers' => array (
                                            'rose'
                                    )
            );

How do I achieve this?

4
  • 1
    stackoverflow.com/questions/6661530/… Commented Apr 1, 2014 at 8:00
  • No, there's no single function that will do it for you. Commented Apr 1, 2014 at 8:07
  • Are the groups mutually exclusive? In other words, can a term appear in multiple groups and do you need to find all applicable groups? Commented Apr 1, 2014 at 8:08
  • Yes they are mutually exclusive. Commented Apr 1, 2014 at 9:35

1 Answer 1

4

Loop it up using a foreach

$keyword='mango';
foreach($array as $k=>$arr)
{
    if(in_array($keyword,$arr))
    {
        echo $k;break;// "prints" fruits
    }
}

Working Demo

Sign up to request clarification or add additional context in comments.

2 Comments

@Jeff, Nah, did you check the demo ?
Just deleted my comment when I realized my mistake! Sorry.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.