Custom Search

# 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:

 "; ?>

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:

 "; ?>

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 5391