Search code examples
phparraysarray-reverse

PHP Need to recursively reverse an array


I need to recursively reverse a HUGE array that has many levels of sub arrays, and I need to preserve all of the keys (which some are int keys, and some are string keys), can someone please help me? Perhaps an example using array_reverse somehow? Also, is using array_reverse the only/best method of doing this?

Thanks :)


Solution

  • Try this:

    function array_reverse_recursive($arr) {
        foreach ($arr as $key => $val) {
            if (is_array($val))
                $arr[$key] = array_reverse_recursive($val);
        }
        return array_reverse($arr);
    }