Showing posts with label recursive array search. Show all posts
Showing posts with label recursive array search. Show all posts

November 25, 2014

Find the Array key in Nested Array

In nested array find the array key for matched value

function recursive_array_search($needle, $haystack) {
    foreach($haystack as $key=>$value) {
        $current_key = $key;
        if($needle === $value
  || (is_array($value) && recursive_array_search($needle,$value) !== false)) {
            return $current_key;
        }
    }
    return false;
}
 
Find the key of the matched element in nested array.

$needle
- String which has to find.

$haystack
- Array elements $needle has to search in this array.