Reversing an Array in PhP

Description:

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

Solution:

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) {
[0]=>
string(1) “c”
[1]=>
string(1) “b”
[“x”]=>
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));

Outputs:

array(3) {
[“a”]=>
string(1) “x”
[“b”]=>
int(10)
[“c”]=>
int(11)
}

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

Advertisements

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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s