FYI: Method for recursive search in multidimensional arrays

Discussion in 'PHP' started by Garkoni, Mar 7, 2013.

  1. #1
    Guys,
    I've broken my head while looking for a way to search for a value in multidimensional arrays. The build-in PHP functions didn't help that much that I expected, but then I've found this great method:
    class ArrayFunc {
    static function recursive_array_search( $needle, $haystack )
        {
            foreach ( $haystack as $key => $value ) {
                $current_key = $key;
                if ( $needle === $value OR ( is_array( $value ) &&
                    self::recursive_array_search( $needle, $value ) !== false )
                ) {
     
                    return $current_key;
                }
            }
            return false;
        }
    }
    PHP:
    usage is easy:
    ArrayFunc::recursive_array_search ( $needle, $haystack );
    PHP:
    $needle - it's what you are looking for
    $haystack - your array
     
    Garkoni, Mar 7, 2013 IP
    Ziggy likes this.
  2. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,999
    Best Answers:
    253
    Trophy Points:
    515
    #2
    Uhm... except your needle is useless as you have no idea which array it actually came from... the outer? the inner, one inside the inner?

    You might want to make it actually return an array, pushing the result of each recursive call onto that array on return.
     
    deathshadow, Mar 7, 2013 IP
  3. Garkoni

    Garkoni Active Member

    Messages:
    213
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    60
    #3
    In my case I just needed to make sure a value exists in a multidimensional array and get the key of the found value. As I used a 2-dimensional array (database table emulation), this function worked for me exactly in the way I posted above.
     
    Garkoni, Mar 11, 2013 IP