5

How does one iterate in reverse over php associative array? https://stackoverflow.com/a/10777617/1032531 gives solutions for a non-associated array.

My attempt:

$a=['5'=>'five','3'=>'three','7'=>'seven'];
var_dump($a);
foreach($a as $k=>$v){echo("$k $v\n");}
$a=array_reverse($a);
var_dump($a);
foreach($a as $k=>$v){echo("$k $v\n");}

produces the following results:

array(3) {
  [5]=>
  string(4) "five"
  [3]=>
  string(5) "three"
  [7]=>
  string(5) "seven"
}
5 five
3 three
7 seven
array(3) {
  [0]=>
  string(5) "seven"
  [1]=>
  string(5) "three"
  [2]=>
  string(4) "five"
}
0 seven
1 three
2 five

I wish to preserve the keys, and return:

array(3) {
  [5]=>
  string(4) "five"
  [3]=>
  string(5) "three"
  [7]=>
  string(5) "seven"
}
5 five
3 three
7 seven
array(3) {
  [7]=>
  string(5) "seven"
  [3]=>
  string(5) "three"
  [5]=>
  string(4) "five"
}
7 seven
3 three
5 five
1
  • Why not use array_reverse and iterate over? Commented Jul 6, 2016 at 13:24

2 Answers 2

9

Just use $a=array_reverse($a,true); instead of $a=array_reverse($a); for keep key.

array_reverse() have a second optional parameter for preserve keys. default value is false.

Read doc here

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Thank you
2

You were very close - you had all the key words already - and just need to remember that the PHP manual is your friend :)

The manual page for array_reverse lists an optional argument $preserve_keys, which defaults to false.

So you just need to change $a=array_reverse($a); to $a=array_reverse($a, true);, and you should get the result you were after.

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.