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.

6 Comments

  1. Gravatar Icon
    Posted June 6, 2008 at 6:20 pm | #

    Well this does exactly what I need. Saved me a lot of time, thanks!

  2. Gravatar Icon
    almost daily
    Posted January 15, 2009 at 8:27 am | #

    Thanks, works great! You might want to replace the &gt and &amp’s to normal characters.

  3. Gravatar Icon
    Pekka
    Posted July 4, 2009 at 5:31 am | #

    Was exactly what I needed, thanks!

  4. Gravatar Icon
    Posted July 29, 2009 at 9:46 am | #

    This is a copy of the php.net manual user contributions.

    However it does not perform correctly.

    What if an occurrence of the needle is found in the array more than once ?

  5. Gravatar Icon
    Sander
    Posted October 3, 2009 at 4:44 pm | #

    Thank you! I also couldn’t get the examples on php.net to work in my script. This worked almost immediately!

  6. Gravatar Icon
    Posted May 12, 2010 at 12:56 am | #

    well this is not what i was searching for , but it surely helped me think of the logic to make my own function for a certain process :) Thanks a lot .

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*

You can follow any discussion on this article with the RSS feed for this post.

About this article

Green Galoshes is a weblog written by Justin D. Henry. This entry was published on or around April 14, 2007.

Categories & Tags

This article is filed under reference. It is further described as , , , , , , .