Home > Articles

chap3_0672323257

  • Print
  • + Share This

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"
  • + Share This
  • 🔖 Save To Your Account

Related Resources

There are currently no related titles. Please check back later.