reverse an array in php

To reverse an array in PHP, you can use the array_reverse function. This function takes an array as its argument and returns a new array with the elements in reverse order.

main.php
$original = array(1, 2, 3, 4, 5);
$reversed = array_reverse($original);
print_r($reversed);
92 chars
4 lines

Output:

main.php
Array
(
    [0] => 5
    [1] => 4
    [2] => 3
    [3] => 2
    [4] => 1
)
75 chars
9 lines

Alternatively, you can use the rsort function. This function sorts an array in reverse order based on its values.

main.php
$original = array(1, 2, 3, 4, 5);
rsort($original);
print_r($original);
72 chars
4 lines

Output:

main.php
Array
(
    [0] => 5
    [1] => 4
    [2] => 3
    [3] => 2
    [4] => 1
)
75 chars
9 lines

related categories

gistlibby LogSnag