PHP array_reverse()
Published Sep 9, 2023
Contribute to Docs
The array_reverse() function reverses the items in an array and returns that reversed array.
Syntax
array_reverse(array, preserve_keys)
array: The array to reverse.preserve_keys: Optional argument that defaults tofalseif omitted. If set totrue, the keys of the original, non-reversed array will be preserved.
Note: If the keys used are non-numeric, they will always be preserved, regardless of whether the
preserve_keysargument is used.
Example
This example returns the reversed array $a using the array_reverse() method.
<?php$a = array(0=>"andrew",1=>"byrne",2=>"hozier",3=>"unreal");print_r(array_reverse($a));?>
This is the output:
Array([0] => unreal[1] => hozier[2] => byrne[3] => andrew)
This example uses the preserve_keys argument while calling the array_reverse() method to return $a.
<?php$a = array(0=>"andrew",1=>"byrne",2=>"hozier",3=>"unreal");print_r(array_reverse($a, true));?>
This is the output:
Array([3] => unreal[2] => hozier[1] => byrne[0] => andrew)
Codebyte Example
The following codebyte example can be run and calls the array_reverse() method three times. The second call uses the preserve_keys argument. And the third call shows that non-numeric keys are preserved automatically, even if the preserve_keys argument is not given.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn PHP on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours