Question

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 :)

Was it helpful?

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);
}

OTHER TIPS

Recursively:

<?php

$a = array(1,3,5,7,9);

print_r($a);

function rev($a) {
  if (count($a) == 1)
    return $a;

  return array_merge(rev(array_slice($a, 1, count($a) - 1)), array_slice($a, 0, 1));
}

$a = rev($a);
print_r($a);

?>

output:

Array
(
    [0] => 1
    [1] => 3
    [2] => 5
    [3] => 7
    [4] => 9
)
Array
(
    [0] => 9
    [1] => 7
    [2] => 5
    [3] => 3
    [4] => 1
)

Reversing a HUGE php array in situ (but not recursively):

function arrayReverse(&$arr){
  if (!is_array($arr) || empty($arr)) {
    return;
  }
  $rev = array();
  while ( false !== ( $val = end($arr) ) ){
    $rev[ key($arr) ] = $val;
    unset( $arr[ key($arr) ] );
  }
  $arr = $rev;
}
//usage
$test = array(5, 'c'=>100, 10, 15, 20);
arrayReverse($test);
var_export($test);
// result: array ( 3 => 20, 2 => 15, 1 => 10, 'c' => 100, 0 => 5, )
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top