Using PHP's array_reverse() Function: Syntax, Examples, and Tips
This article explains PHP's array_reverse() function, covering its syntax, optional parameters, and multiple code examples that demonstrate reversing indexed arrays, associative arrays with key preservation, and combining with other array functions for more complex operations.
In PHP, there are many convenient and practical functions for developers. One of them is the array_reverse() function, which can reverse the order of elements in a given array. This article details its usage and provides code examples.
The syntax of array_reverse() is as follows:
array_reverse ( array $array [, bool $preserve_keys = FALSE ] ) : arrayThe function accepts an array and returns a new array with elements in reverse order. The optional $preserve_keys parameter, when set to TRUE , retains the original keys; otherwise, new numeric keys are generated.
Below are several examples demonstrating the use of array_reverse() :
Example 1: Reverse an Indexed Array
$fruits = array("apple", "banana", "cherry", "date");
$reversed_fruits = array_reverse($fruits);
print_r($reversed_fruits);Output:
Array
(
[0] => date
[1] => cherry
[2] => banana
[3] => apple
)Example 2: Reverse an Associative Array While Preserving Keys
$colors = array(
"red" => "#FF0000",
"green" => "#00FF00",
"blue" => "#0000FF"
);
$reversed_colors = array_reverse($colors, true);
print_r($reversed_colors);Output:
Array
(
[blue] => #0000FF
[green] => #00FF00
[red] => #FF0000
)Example 3: 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);Output:
Array
(
[0] => 9
[1] => 5
[2] => 4
[3] => 3
[4] => 2
[5] => 1
[6] => 1
)From the examples, the array_reverse() function is simple and easy to use. You can choose whether to preserve keys and combine it with other array functions such as sort() for more complex tasks.
Conclusion
The array_reverse() function is a very useful PHP function that conveniently reverses the order of array elements. It works for both indexed and associative arrays, and the optional parameter allows you to keep original keys if needed. In real development, this function is often used for array manipulation, especially when re‑ordering existing data.
After reading this article and reviewing the code examples, readers should have a solid understanding of array_reverse() and be able to apply it flexibly to improve code efficiency and readability.
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.