Description:
Having an array, how to easily do to reverse the order of the elements.
Solution:
PhP offers an out-of-the box solution to this issue. It is the function array_reverse() which inverts the order of the array elements. A point to take care of is that the key association is lost only for elements which have numeric keys:
$a = array (’x’ => ’a’, 10 => ’b’, ’c’);
var_dump (array_reverse ($a));
This outputs:
array(3) {
[0]=>
string(1) “c”
[1]=>
string(1) “b”
["x"]=>
string(1) “a”
}
Not to be confused with array_flip() which changes the value of the element with the value of the key:
var_dump (array_flip ($a));
Outputs:
array(3) {
["a"]=>
string(1) “x”
["b"]=>
int(10)
["c"]=>
int(11)
}
Note: the 3rd element will be 11 as the array keys are consecutive numbers, unless mentioned otherwise.