Master PHP’s array_reverse: Reverse Arrays Easily with Code Examples
Learn how to use PHP’s array_reverse function to flip array elements, preserve keys when needed, and combine it with other array functions like sort, through clear explanations and practical code snippets that demonstrate reversing indexed, associative, and numeric arrays.
In PHP there are many handy functions for developers; one of them is array_reverse(), which reverses the order of elements in a given array.
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 the examples we can see that array_reverse() is very simple and easy to use. You can choose whether to keep the original keys and combine it with other array functions such as sort() to achieve more complex operations.
In summary, array_reverse() is a highly practical PHP function that conveniently reverses array elements. It works for both indexed and associative arrays, and the optional parameter allows you to preserve keys. In real development it is often used when you need to rearrange existing data.
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.
