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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With