One way to reverse the order of elements in an array in PHP is by using the array_reverse()
function. Here's an example:
$array = [1, 2, 3, 4, 5];
$reversedArray = array_reverse($array);
print_r($reversedArray);
The output will be:
Array
(
[0] => 5
[1] => 4
[2] => 3
[3] => 2
[4] => 1
)
Alternatively, you can use the array_reverse()
function with the second parameter true
to preserve the keys of the original array:
$array = [1 => 'a', 2 => 'b', 3 => 'c'];
$reversedArray = array_reverse($array, true);
print_r($reversedArray);
The output will be:
Array
(
[3] => c
[2] => b
[1] => a
)
Note that the original array is not modified, and a new array with reversed elements is returned.