Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterate reverse over php associative array

Tags:

arrays

php

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
like image 215
user1032531 Avatar asked Jan 06 '23 18:01

user1032531


1 Answers

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

like image 172
Alexis Avatar answered Jan 15 '23 21:01

Alexis