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
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”.
If we are using an associative array we cannot sort an array by using the sort() function. If we apply the sort() function on an associative array, it is sorted by the numeric value of the index. To sort an associative array we need to use the asort() function to keep keys and values together as they are sorted.
The following code creates an associative array containing the three flowers and their associated prices, and then sorts the array into ascending price order:
|
The above example will output:
orchid costs 2.00 dollars
daisy costs 4.00 dollars
rose costs 5.00 dollars
The asort() function orders the array according to the value of each element. In the array, the values are the prices and the keys are the names of the flowers.
If instead of sorting by price we want to sort by flower name, we use ksort() function to sort an associative array according to the key.
The following code will result in the keys of the array being ordered alphabetically:
|
Output will be the following:
daisy costs 4.00 dollars
orchid costs 2.00 dollars
rose costs 5.00 dollars
Sorting Arrays in the Reverse Order
We discussed sort(), asort(), and ksort() functions. All these functions sort array in the ascending order. Each of them has corresponding function that sorts an array in the descending order. These reverse functions are called rsort(), arsort() and krsort() respectively.
Reverse sorting functions are used the same way as usual sorting functions. Rsort() function sorts one-dimensional numerically indexed array by the values in reverse order. Arsort() function sorts one-dimensional associative array by the values in reverse order. Krsort() function sorts one-dimensional associative array by the keys in reverse order.