3.15 Reversing Order


You want to process an array in reverse order or permanently reverse the order of the array.

Technique

Use the array_reverse() function to reverse the array:

 <?php $ar = array_reverse ($ar); ?> 

Or use a for loop to process the array backward:

 <?php for ($i = count ($my_array) - 1; $i >= 0; $i--) {     // Loop backwards through the array } ?> 

Comments

The first example actually reverses the entire array; if you have an enormous array, this approach can be inefficient as far as speed is concerned . The second method loops backwards through the entire array, which is much faster on larger arrays because it saves a step.

If you are sorting an array, you should automatically reverse your sort in the array sort . This can be done by using either arsort() for processing associative arrays or rsort() for arrays.

 $fruits = array ("Oranges", "Apples", "Pears", "Bananas"); $fruits = rsort ($fruits); // $fruits is now "Pears, Oranges, Bananas, Apples" 


PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

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