Search for a key in an array, recursively Search for a key in an array, recursively php php

Search for a key in an array, recursively


Maybe it's overkill, but it's funny to use RecursiveIterators :)

UPDATE: Maybe it was overkill with old versions of PHP, but with >=5.6 (specially with 7.0) I would totally use this without doubt.

function recursiveFind(array $haystack, $needle){    $iterator  = new RecursiveArrayIterator($haystack);    $recursive = new RecursiveIteratorIterator(        $iterator,        RecursiveIteratorIterator::SELF_FIRST    );    foreach ($recursive as $key => $value) {        if ($key === $needle) {            return $value;        }    }}

UPDATE: Also, as of PHP 5.6, with generators you can easily iterate over all elements which pass the filter, not only the first one:

function recursiveFind(array $haystack, $needle){    $iterator  = new RecursiveArrayIterator($haystack);    $recursive = new RecursiveIteratorIterator(        $iterator,        RecursiveIteratorIterator::SELF_FIRST    );    foreach ($recursive as $key => $value) {        if ($key === $needle) {            yield $value;        }    }}// Usageforeach (recursiveFind($haystack, $needle) as $value) {    // Use `$value` here}


function array_search_key( $needle_key, $array ) {  foreach($array AS $key=>$value){    if($key == $needle_key) return $value;    if(is_array($value)){      if( ($result = array_search_key($needle_key,$value)) !== false)        return $result;    }  }  return false;} 

this will work !

you need to stop the recursive deep search, by return false and then check it in the function.

you can find more examples of functions (like using RecursiveArrayIterator and more) in this link :http://php.net/manual/en/function.array-search.php


The answer provided by xPheRe was extremely helpful, but didn't quite solve the problem in my implementation. There are multiple nested associative arrays in our data structure, and there may be multiple occurrences of any given key.

In order to suit our purposes, I needed to implement a holder array that was updated while traversing the entire structure, instead of returning on the first match. The real work was provided by another poster, but I wanted to say thanks and share the final step that I had to cover.

public function recursiveFind(array $array, $needle){    $iterator  = new RecursiveArrayIterator($array);    $recursive = new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::SELF_FIRST);    $aHitList = array();    foreach ($recursive as $key => $value) {        if ($key === $needle) {            array_push($aHitList, $value);        }    }    return $aHitList;}