1

I'm trying to loop through a sub array (which is part of a multidimensional array) and check if there's a pair of key/value. If the pair is found, I want to return the key of the sub array in which it was found.

Unfortunately it seems the key() function doesn't work with foreach.

How would I change this code to use a while loop?

If you have a better suggestion let me know.

foreach ($subarray as $subkey => $subvalue) {           
    if ($subkey == 'key_value' AND $subvalue = 'value') {
        return key($subarray);
    }
}

The array keys are not numeric. Here's a example :

$array['books'] = array('quantity' => 10, 'title' => 'Something')
$array['dvds'] = array('quantity' => 30, 'title' => 'Something else')

Searching for a "title" called "something", the function should return "books" because that's the key where the pair of sub key/value is found.

Thanks for your help.

1 Answer 1

3
$array['books'] = array('quantity' => 10, 'title' => 'Something');
$array['dvds'] = array('quantity' => 30, 'title' => 'Something else');

foreach($array as $key => $value) {
  if ($value['title'] === 'Something') {
    return $key;
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

If you are using return, where is the function that it is returning from? Please update this answer because it may confuse/mislead future readers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.