- Chapter 3: Using Arrays
- 1 Declaring an Array
- 2 Printing Out an Array
- 3 Eliminating Duplicate Elements
- 4 Enlarging or Shrinking an Array
- 5 Merging Arrays
- 6 Iteratively Processing Elements in an Array
- 7 Accessing the Current Element in an Array
- 8 Accessing Different Areas of an Array
- 9 Searching an Array
- 10 Searching for the Different Elements in Two Arrays
- 11 Randomizing the Elements of an Array
- 12 Determining the Union, Intersection, or Difference Between Two Arrays
- 13 Sorting an Array
- 14 Sorting Sensibly
- 15 Reversing Order
- 16 Perl-Based Array Manipulation Features
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"