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.

20 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 .

  7. Gravatar Icon
    Tom
    Posted October 20, 2010 at 4:03 am | #

    I get the following error:
    Parse error: syntax error, unexpected ‘=’, expecting ‘)’ in myphppage.php on line 132

    Line 132 being : foreach( $haystack as $key => $val ) {

    Any ideas ?

  8. Gravatar Icon
    Posted February 11, 2011 at 12:20 am | #

    Be sure your multidimensional array contain boolean true false values. if it contains call the function with $strict=true,function is awesome and very helpful.

  9. Gravatar Icon
    minh nhut
    Posted April 3, 2011 at 8:19 am | #

    help me.if used recursion:
    bool contains( char *haystack, char *needle)

  10. Gravatar Icon
    Vinny
    Posted May 27, 2011 at 11:37 am | #

    How would I modify this to work with this array: http://i56.tinypic.com/345hdex.png

  11. Gravatar Icon
    Sarita
    Posted July 6, 2011 at 7:23 am | #

    Great… exactly what i wanted… thanx..

  12. Gravatar Icon
    Posted August 18, 2011 at 6:23 pm | #

    I’m back with a solution.
    Using these 2 functions will search multidimensional arrays and return ALL matching paths (items) NOT just a single item.

    if(!function_exists(‘array_search_recursive’)){
    function array_search_recursive($needle, $haystack, $key_lookin=”"){
    $path = NULL;
    if (!empty($key_lookin) && array_key_exists($key_lookin, $haystack) && $needle === $haystack[$key_lookin]) {
    $path[] = $key_lookin;
    } else {
    foreach($haystack as $key => $val) {
    if (is_scalar($val) && $val === $needle && empty($key_lookin)) {
    $path[] = $key;
    break;
    } elseif (is_array($val) && $path = array_search_recursive($needle, $val, $key_lookin)) {
    array_unshift($path, $key);
    break;
    }
    }
    }
    return $path;
    }
    }

    // Recursive backtracking function for multidimensional array search
    if(!function_exists(‘search_r’)){
    function search_r($value, $array){
    $results = array();

    if(is_array($array)){
    $path = array_search_recursive($value, $array);
    if (is_array($path) && count($path) > 0){
    $results[] = $path;
    unset($array[$path[0]]);
    $results = array_merge($results, search_r($value, $array));
    }else{

    }
    }

    return $results;
    }
    }

  13. Gravatar Icon
    Posted November 23, 2011 at 7:19 am | #

    Works great! Make sure to replace > with a greater than symbol and the $amp; with the Ampersand (6x). Thanks for providing this.

  14. Gravatar Icon
    Posted March 16, 2012 at 6:27 pm | #

    thank you very much!

    saved enough time to search value in a multi dimentional array

  15. Gravatar Icon
    Posted August 21, 2012 at 4:48 am | #

    great ! helped me to solve my pb thx :)

  16. Gravatar Icon
    Tyrel Richey
    Posted September 20, 2012 at 1:23 pm | #

    Thank you

  17. Gravatar Icon
    Posted September 21, 2012 at 7:15 am | #

    here is a easy search function

    function search($array, $key, $value)
    {
    $results = array();

    if (is_array($array))
    {
    if (isset($array[$key]) && $array[$key] == $value)
    $results[] = $array;

    foreach ($array as $subarray)
    $results = array_merge($results, search($subarray, $key, $value));
    }

    return $results;
    }

  18. Gravatar Icon
    Zeeshan
    Posted February 18, 2013 at 10:09 am | #

    function recursiveSearch($some_arr){
    $found = array(); //create a new array
    foreach($some_arr as $key => $val) {
    //echo “KEY::”.$key.”VALue::”.$val.”";
    if($val == ’1′){//replace ’1′ with the value you want to search
    $found[] = $key;
    }
    }
    return $found;
    }

  19. Gravatar Icon
    ghires
    Posted June 26, 2013 at 5:07 pm | #

    This function is working great, but how can it be modified to search for a “partial” value.

    Thanks!

  20. Gravatar Icon
    Posted August 2, 2014 at 6:17 pm | #

    As tthe admin of this website is working, no hesitation very ssoon it will be well-known, due to
    its feature contents.

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 , , , , , , .