Sorting Arrays
Sorting related data stored in an array is often useful. You can easily take a one-dimensional array and sort it into order.
Using sort()
The following code showing the sort() function results in the array being sorted into ascending alphabetical order:
$products = array( 'Tires', 'Oil', 'Spark Plugs' ); sort($products);
The array elements will now appear in the order Oil, Spark Plugs, Tires.
You can sort values by numerical order, too. If you have an array containing the prices of Bob's products, you can sort it into ascending numeric order as follows:
$prices = array( 100, 10, 4 ); sort($prices);
The prices will now appear 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.
The function also has an optional second parameter. You may pass one of the constants SORT_REGULAR (the default), SORT_NUMERIC, or SORT_STRING. The ability to specify the sort type is useful when you are comparing strings that might contain numbers, for example, 2 and 12. Numerically, 2 is less than 12, but as strings '12' is less than '2'.
Using asort() and ksort() to Sort Arrays
If you are using an array with descriptive keys to store items and their prices, you need to use different kinds of sort functions to keep keys and values together as they are sorted.
The following code creates an 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, you want to sort by description, you can use ksort(), which sorts by key rather than value. The following code results 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
The three different sorting functionssort(), asort(), and ksort()sort an array into ascending order. Each function has a matching reverse sort function to sort an array into descending order. The reverse versions are called rsort(), arsort(), and krsort().
You use the reverse sort functions in the same way you use the ascending sort functions. The rsort() function sorts a single-dimensional numerically indexed array into descending order. The arsort() function sorts a one-dimensional array into descending order using the value of each element. The krsort() function sorts a one-dimensional array into descending order using the key of each element.