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 Courses
php Courses
php Courses
Using PHP's array_reverse() Function to Reverse Arrays

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<br/>(<br/>    [0] => date<br/>    [1] => cherry<br/>    [2] => banana<br/>    [3] => apple<br/>)

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<br/>(<br/>    [blue] => #0000FF<br/>    [green] => #00FF00<br/>    [red] => #FF0000<br/>)

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<br/>(<br/>    [0] => 1<br/>    [1] => 1<br/>    [2] => 2<br/>    [3] => 3<br/>    [4] => 4<br/>    [5] => 5<br/>    [6] => 9<br/>)

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendPHPCode ExamplesArraysarray_reverse
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.