Sorting Arrays
It is often useful to sort related data stored in an array. Taking a one-dimensional array and sorting it into order is quite easy.
Using sort()
The following code results in the array being sorted into ascending alphabetical order:
$products = array( 'Tires', 'Oil',
'Spark Plugs' ); sort($products);
Our array elements will now be in the order Oil, Spark Plugs, Tires.
We can sort values by numerical order too. If we have an array containing the prices of Bob's products, we can sort it into ascending numeric order as shown:
$prices = array( 100, 10, 4 ); sort($prices);
The prices will now be in the order 4, 10, 100.
Note that the sort function is case sensitive. All capital letters come before all lowercase letters. So "A" is less than "Z", but "Z" is less than "a".
Using asort() and ksort() to Sort Associative Arrays
If we are using an associative array to store items and their prices, we need to use different kinds of sort functions to keep keys and values together as they are sorted.
The following code creates an associative array containing the three products and their associated prices, and then sorts the array into ascending price order.
$prices = array( 'Tires'=>100, 'Oil'=>10, 'Spark Plugs'=>4 ); asort($prices);
The function asort() orders the array according to the value of each element. In the array, the values are the prices and the keys are the textual descriptions. If instead of sorting by price we want to sort by description, we use ksort(), which sorts by key rather than value. This code will result in the keys of the array being ordered alphabeticallyOil, Spark Plugs, Tires.
$prices = array( 'Tires'=>100, 'Oil'=>10, 'Spark Plugs'=>4 ); ksort($prices);
Sorting in Reverse
You have seen sort(), asort(), and ksort(). These three different sorting functions all sort an array into ascending order. Each of these functions has a matching reverse sort function to sort an array into descending order. The reverse versions are called rsort(), arsort(), and krsort().
The reverse sort functions are used in the same way as the sorting functions. The rsort() function sorts a single dimensional numerically indexed array into descending order. The arsort() function sorts a one-dimensional associative array into descending order using the value of each element. The krsort() function sorts a one-dimensional associative array into descending order using the key of each element.