Understanding PHP's array_reverse() Function: Syntax, Parameters, Usage, and Examples
This article explains PHP's array_reverse() function, covering its purpose, syntax, parameters, return values, usage examples for indexed and associative arrays, key preservation options, and important considerations for developers working with array manipulation.
As a widely used server-side scripting language, PHP offers a powerful function library that simplifies many programming tasks. Among them, the array_reverse() function is a commonly used array function. This article explores its usage and characteristics.
1. What is the array_reverse() function?
The array_reverse() function in PHP reverses the order of elements in an array. It works with indexed and associative arrays and returns a new array without altering the original keys.
2. Function syntax and parameters
The basic syntax is:
<code>array array_reverse(array $array [, bool $preserve_keys = FALSE]);</code>Parameters:
$array: required, the array to be reversed.
$preserve_keys: optional, whether to preserve the original keys (default FALSE). If TRUE, the reversed array retains the original keys.
3. How to use the function
Using array_reverse() is straightforward: pass the array to be reversed as the argument. Below are examples.
① Reverse an indexed array:
<code>$numbers = array(1, 2, 3, 4, 5);
$rev_numbers = array_reverse($numbers);
print_r($rev_numbers); // Output: Array ( [0] => 5 [1] => 4 [2] => 3 [3] => 2 [4] => 1 )</code>② Reverse an associative array:
<code>$infos = array('name' => 'Tom', 'age' => 20, 'sex' => 'male');
$rev_infos = array_reverse($infos);
print_r($rev_infos); // Output: Array ( [sex] => male [age] => 20 [name] => Tom )</code>③ Preserve original keys:
<code>$fruits = array('a' => 'apple', 'b' => 'banana', 'c' => 'cherry');
$rev_fruits = array_reverse($fruits, true);
print_r($rev_fruits); // Output: Array ( [c] => cherry [b] => banana [a] => apple )</code>4. Return value
The function returns a new array containing all elements of the original array in reverse order. If the original array is empty, an empty array is returned. When $preserve_keys is TRUE, the keys in the new array remain the same as the original.
5. Precautions
When using array_reverse() , keep in mind:
The function works only on arrays, not other data types.
If $preserve_keys is TRUE, original keys are kept, but their data types may change (e.g., integer keys become strings).
An empty input array yields an empty result.
Conclusion
The array_reverse() function is a practical PHP array utility that conveniently reverses element order and returns a new array, helping to write more efficient and concise code.
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.