PHP How to Sort an Array

Dec 04, 2008 Author: Jenna

It is often necessary to arrange the elements in an array in numerical order from highest to lowest values (descending order) or vice versa (ascending order). If the array contains string values, alphabetical order may be needed. Sorting a one-dimensional arrays is quite easy.

  • Sorting numerically indexed arrays
  • Sorting associative arrays
  • Sorting arrays in the reverse order

Sorting Numerically Indexed Arrays

At first we will consider an array which contains string values. The code below sorts array elements in ascending alphabetical order:

<?php
$flowers = array("rose", "daisy" , "orchid", "tulip", "camomile");
sort($flowers);

for ($i=0; $i <= 4; $i++) //prints the array elements
    echo $flowers[$i]."<br \>";
?>

Now array elements will go in the alphabetical order. Output will be the following:

camomile
daisy
orchid
rose
tulip

We can sort values by numerical order too. If we have an array containing the prices of  flowers, we can sort it into ascending numeric order. Have a look at the example:

<?php
$prices = array(1.25, 0.75 , 1.15, 1.00, 0.50);
sort($prices);

for ($i=0; $i <= 4; $i++) //prints the array elements
    echo $prices[$i]."<br \>";
?>

The prices will now be in the following order:

0.50
0.75
1.00
1.15
1.25

Note that the sort function is case sensitive, i.e. all capital letters come before all lowercase letters. So "A" is less than "Z", but "Z" is less than "a".

Continue to the next part of this Tutorial

tags: how sort an Array

views 4851
  1. Add New Comment