Master PHP’s array_reverse(): Reverse Arrays with Ease
This article explains PHP’s array_reverse() function, covering its syntax, optional parameters, and practical code examples that demonstrate reversing indexed arrays, associative arrays with key preservation, and combining reversal with sorting for more complex array manipulations.
PHP provides many convenient functions for developers, and array_reverse() is one that reverses the order of elements in an array. This article details its usage and shows code examples.
The syntax of array_reverse() is:
array_reverse ( array $array [, bool $preserve_keys = FALSE ] ) : arrayThe function accepts an array and returns a new array with elements reversed. The optional $preserve_keys parameter, when set to TRUE, keeps the original keys; otherwise, new numeric keys are generated.
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 these examples, it is clear that array_reverse() is simple and easy to use. You can choose whether to preserve original keys and combine it with other array functions such as sort() for more complex operations.
Conclusion
The array_reverse() function is a very practical tool in PHP for reversing the order of array elements. It works with both indexed and associative arrays, and the optional parameter lets you keep original keys. In real development, this function is often used when you need to rearrange existing data efficiently.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
