views:

41

answers:

4
private function find($needle, $haystack) {
    foreach ($haystack as $name => $file) {
        if ($needle == $name) {
            return $file;
        } else if(is_array($file)) { //is folder
            return $this->find($needle, $file); //file is the new haystack
        }               
    }

    return "did not find";
}

Hey, this method searches for a specific key in an associative array and returns the value associated with it. There's some problem with the recursion. Any clue?

A: 

Look at this : http://www.php.net/manual/fr/function.array-search.php#88047 ^^

MatTheCat
+3  A: 
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

Haim Evgi
A: 

To answer your question, you're never letting the loop advance past the first entry.

Phil Brown
what do you mean exactly?
Marreman
Sorry, my comment above wasn't very accurate. What you're function is not doing is advancing past the first array value as you always `return`. See in Haim's solution that the result from the recursive call is tested first.
Phil Brown
A: 

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

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