Mastering PHP’s array_reverse(): Reverse Arrays with Ease
This guide explains PHP’s array_reverse() function, covering its purpose, syntax, parameters, return values, and practical examples for indexed, associative, and key‑preserving array reversals, while highlighting important usage notes to help developers apply it correctly in their code.
1. What is array_reverse()?
array_reverse()is a PHP array function that reverses the order of elements in an array, works with indexed and associative arrays, and returns a new array without altering the original keys.
2. Syntax and parameters
Basic syntax:
array array_reverse(array $array [, bool $preserve_keys = FALSE]);Parameters: $array: required, the array to reverse. $preserve_keys: optional, whether to keep original keys; default FALSE; if TRUE, keys are preserved.
3. Usage examples
Examples:
① Indexed array reversal:
$numbers = array(1, 2, 3, 4, 5);
$rev_numbers = array_reverse($numbers);
print_r($rev_numbers); // Array ( [0] => 5 [1] => 4 [2] => 3 [3] => 2 [4] => 1 )② Associative array reversal:
$infos = array('name' => 'Tom', 'age' => 20, 'sex' => 'male');
$rev_infos = array_reverse($infos);
print_r($rev_infos); // Array ( [sex] => male [age] => 20 [name] => Tom )③ Preserve keys:
$fruits = array('a' => 'apple', 'b' => 'banana', 'c' => 'cherry');
$rev_fruits = array_reverse($fruits, true);
print_r($rev_fruits); // Array ( [c] => cherry [b] => banana [a] => apple )4. Return value
The function returns a new array with elements in reverse order. If the input array is empty, an empty array is returned. When $preserve_keys is TRUE, the returned array keeps the original keys.
5. Important notes
array_reverse()works only on arrays, not other data types.
If $preserve_keys is TRUE, original integer keys become strings in the result.
An empty input array yields an empty result.
Conclusion
array_reverse()is a practical PHP function for efficiently reversing array elements while optionally preserving keys, helping to write cleaner and more concise code.
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.
