Reversing an Array in PhP


Having an array, how to easily do to reverse the order of the elements.


PhP offers an out-of-the box solution to this issue. It is the function array_reverse() which inverts the order of the array elements. A point to take care of is that the key association is lost only for elements which have numeric keys:

$a = array (’x’ => ’a’, 10 => ’b’, ’c’);
var_dump (array_reverse ($a));

This outputs:

array(3) {
string(1) “c”
string(1) “b”
string(1) “a”

Not to be confused with array_flip() which changes the value of the element with the value of the key:

var_dump (array_flip ($a));


array(3) {
string(1) “x”

Note: the 3rd element will be 11 as the array keys are consecutive numbers, unless mentioned otherwise.


About admin

Just another php developer trying to give something back to the community.
This entry was posted in PhP and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s