PHP array_reverse() function
The array_reverse()
function in PHP is used to reverse the order of the elements in an array. This function does not modify the original array; instead, it returns a new array with the elements in the opposite order.
Syntax:
Parameters:
- $array: The input array that you want to reverse.
- $preserve_keys: (Optional) A boolean parameter that determines whether to preserve the original keys. If set to
true
, the keys will be preserved in the returned array. If set tofalse
(the default), the keys will be re-indexed starting from0
.
Return Value:
- Returns a new array containing the elements of the original array in reverse order.
Example 1: Basic Reversal
In this example, we demonstrate how to use array_reverse()
to reverse a simple indexed array.
Output:
In this case, the elements of the original array are reversed, resulting in a new array.
Example 2: Preserving Keys
You can choose to preserve the original keys by setting the second parameter to true
.
Output:
Here, the keys are preserved, and the resulting array maintains the original key-value associations.
Example 3: Reversing an Empty Array
If you call array_reverse()
on an empty array, it will return an empty array.
Output:
In this case, the output is simply an empty array, as there are no elements to reverse.
Example 4: Reversing Multidimensional Arrays
You can use array_reverse()
with multidimensional arrays as well, although it will only reverse the top-level array.
Output:
Here, the top-level array is reversed, but the inner arrays remain unchanged.
Practical Usage:
array_reverse()
is useful for:- Reversing the order of elements in a dataset for processing or display.
- Implementing functionalities like undo operations where the last item added needs to be processed first.
- Displaying items in reverse order, such as in a stack or a timeline.
Summary:
array_reverse($array, $preserve_keys)
reverses the order of elements in the specified array and returns a new array.- You can choose to preserve the original keys or re-index them.
- This function is versatile for various use cases involving array manipulation in PHP, making it a handy tool for developers.