Current Location: Home> Latest Articles> In-Depth Analysis of PHP array_reverse() Function: Principles and Practical Examples

In-Depth Analysis of PHP array_reverse() Function: Principles and Practical Examples

gitbox 2025-06-28

Introduction to the array_reverse() Function

The array_reverse() function is a powerful tool provided by PHP to reverse the order of elements in an array. By using this function, developers can reorder the elements in an array in reverse and return a new array.

Syntax of the array_reverse() Function

array_reverse(array $array, bool $preserve_keys = false): array

Parameter Explanation

array: Required. The array that you want to reverse.

preserve_keys: Optional. Specifies whether to preserve the original keys of the array. Default is false, meaning keys are not preserved.

Return Value

The function returns a new array with the order of elements reversed.

How the array_reverse() Function Works

The principle behind the array_reverse() function is quite simple. When the function is called, it first checks whether the preserve_keys parameter is passed. If true is passed, the function will reverse the array while keeping the key-value pairs. If false is passed or the parameter is not provided, the function will use incremental integers as keys for the new array.

Next, the function creates a new empty array based on the length of the original array and starts looping through the original array from the end, adding each element to the new array. Finally, it returns the new array with the reversed order.

Common Usage of the array_reverse() Function

Basic Usage

The following example demonstrates how to use the array_reverse() function to reverse an array:


$fruits = array('apple', 'banana', 'orange');
$reversed_fruits = array_reverse($fruits);
print_r($reversed_fruits);

Running the above code outputs the following:

Array
(
    [0] => orange
    [1] => banana
    [2] => apple
)

As shown, the original array [apple, banana, orange] has been reversed to [orange, banana, apple].

Preserving Keys

If you pass true to the preserve_keys parameter, the function will preserve the original keys of the array. Here’s an example:


$fruits = array(
    'a' => 'apple',
    'b' => 'banana',
    'o' => 'orange'
);
$reversed_fruits = array_reverse($fruits, true);
print_r($reversed_fruits);

The output will be:

Array
(
    [o] => orange
    [b] => banana
    [a] => apple
)

In this case, the array's keys remain unchanged, but the values are reversed.

Conclusion

PHP's array_reverse() function is a convenient tool for reversing the order of array elements. With a simple function call, you can easily reverse an array, and you can also choose whether or not to preserve the keys based on your needs. Mastering this function will make array manipulation much more efficient in your PHP development.

I hope this article helps you better understand and use the array_reverse() function to improve your PHP programming skills.