Using PHP's array_reverse() Function to Reverse Arrays
This article explains the PHP array_reverse() function, its syntax, optional preserve_keys parameter, and provides multiple code examples demonstrating how to reverse indexed and associative arrays and combine the function with sort() for more complex array manipulations.
PHP provides many useful functions, one of which is array_reverse() that reverses the order of elements in an array.
The syntax is array_reverse ( array $array [, bool $preserve_keys = FALSE ] ) : array where the optional $preserve_keys parameter determines whether original keys are kept.
Example 1 shows reversing an indexed array:
$fruits = array("apple", "banana", "cherry", "date");
$reversed_fruits = array_reverse($fruits);
print_r($reversed_fruits);The output is:
Array
(
[0] => date
[1] => cherry
[2] => banana
[3] => apple
)Example 2 demonstrates reversing an associative array while preserving keys:
$colors = array(
"red" => "#FF0000",
"green" => "#00FF00",
"blue" => "#0000FF"
);
$reversed_colors = array_reverse($colors, true);
print_r($reversed_colors);Result:
Array
(
[blue] => #0000FF
[green] => #00FF00
[red] => #FF0000
)Example 3 combines array_reverse() with sort() to reverse and then sort an indexed array.
$numbers = array(3, 1, 4, 1, 5, 9, 2);
$reversed_sorted_numbers = array_reverse($numbers);
sort($reversed_sorted_numbers);
print_r($reversed_sorted_numbers);The final sorted array is:
Array
(
[0] => 1
[1] => 1
[2] => 2
[3] => 3
[4] => 4
[5] => 5
[6] => 9
)In summary, array_reverse() is a simple yet powerful PHP function for reversing arrays, with an optional parameter to preserve keys, and it can be combined with other array functions such as sort() for more complex operations.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.