Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
add comment (requires an account with 50 reputation)

1 Answer

up vote 2 down vote accepted
$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;
  }
}
share|improve this answer
Thanks! I was making it more complicated than it needed to be! – Enkay Aug 18 '11 at 21:37
add comment (requires an account with 50 reputation)

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.