Recursive (multidimensional) array search in PHP

If you are looking to do a recursive array search in PHP (and don’t feel like writing your own), you might have tried a number of the functions described in the comments section of the array_search page in the manual. Just for future reference, I have tried a few, but not all of them worked for me. This one did:

    /**
     * Searches haystack for needle and 
     * returns an array of the key path if 
     * it is found in the (multidimensional) 
     * array, FALSE otherwise.
     *
     * @mixed array_searchRecursive ( mixed needle, 
     * array haystack [, bool strict[, array path]] )
     */
 
function array_searchRecursive( $needle, $haystack, $strict=false, $path=array() )
{
    if( !is_array($haystack) ) {
        return false;
    }
 
    foreach( $haystack as $key => $val ) {
        if( is_array($val) && $subPath = array_searchRecursive($needle, $val, $strict, $path) ) {
            $path = array_merge($path, array($key), $subPath);
            return $path;
        } elseif( (!$strict && $val == $needle) || ($strict && $val === $needle) ) {
            $path[] = $key;
            return $path;
        }
    }
    return false;
}

The comment directly following it (above it, actually) describes a modified version that would let you restrict your search by key.

24 Comments