Blog entries   |  [PHP] Recursive array search with multiple results

[PHP] Recursive array search with multiple results

Ok, so for UnlockSamsungOnline.com I needed a function to search in a multidimensional array with an unknown dept for values and returning the base keys. So first I started at php.net and I searched google. It was easy to find such a function when it just presented one result or just a ‘yes, the value is in your array’ result, however I needed all the keys from the array in which a particular string was found in any of its sub-arrays.

Well I came to the conclusion it was either just very hard to find or not yet out there published in the wild, so I took the smallest and simplest function I could find which just provided me with the first key when the needle was found and modified it so it does exactly what I want. Here it is I hope it can help you out at well:

function recursive_array_search($needle,$haystack,$subloop = false) {
    if($subloop === false) $resarr = array();
    foreach($haystack as $key=>$value) {
        $current_key=$key;
        if(is_string($needle)) $needle = trim(strtolower($needle));
        if(is_string($value)) $value = trim(strtolower($value));
        if($needle===$value OR (is_array($value) && recursive_array_search($needle,$value,true) === true)) {
            $resarr[] = $current_key;
            if($subloop === true) return true;
        }
    }
    return $resarr;
}

The function will return an array with all keys in which your needle is found.




3 Responses to [PHP] Recursive array search with multiple results

  1. Robin C. Reply

    May 11, 2012 at 6:00 pm

    Eureka! I’ve been lost for hours creating/finding a multidimensional array search that returns an array with multiple found keys. Thank you very much!

    You’re my saviour!

  2. Steven Reply

    May 12, 2012 at 6:03 am

    Hi Robin,

    Glad to hear it helped you out!

  3. Pramod Reply

    September 13, 2012 at 9:16 am

    This will check only first occurrence of that value in inner array.

Leave a Reply

Your email address will not be published. Required fields are marked *