2

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

2
  • 2
    Any reason why you can't just walk it in reverse order? Commented Nov 5, 2010 at 5:55
  • Anyways, decided to walk it in reverse order, but seems like too much code since I just repeat the same 20 lines of code for each if statement in REVERSE ORDER... argg Commented Nov 5, 2010 at 6:35

3 Answers 3

11

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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
)

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.