Recipe 4.15. Reversing an Array


4.15.1. Problem

You want to reverse the order of the elements in an array.

4.15.2. Solution

Use array_reverse( ):

$array = array('Zero', 'One', 'Two'); $reversed = array_reverse($array);

4.15.3. Discussion

The array_reverse( ) function reverses the elements in an array. However, it's often possible to avoid this operation. If you wish to reverse an array you've just sorted, modify the sort to do the inverse. If you want to reverse a list you're about to loop through and process, just invert the loop. Instead of:

for ($i = 0, $size = count($array); $i < $size; $i++) {     ... }

do the following:

for ($i = count($array) - 1; $i >=0 ; $i--) {     ... }

However, as always, use a for loop only on a tightly packed array.

Another alternative would be, if possible, to invert the order elements are placed into the array. For instance, if you're populating an array from a series of rows returned from a database, you should be able to modify the query to ORDER DESC. See your database manual for the exact syntax for your database.

4.15.4. See Also

Documentation on array_reverse( ) at http://www.php.net/array-reverse.




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net