Specifications

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.
Sorting Multidimensional Arrays
Sorting arrays with more than one dimension, or by something other than alphabetical or
numerical order, is more complicated. PHP knows how to compare two numbers or two text
strings, but in a multidimensional array, each element is an array. PHP does not know how to
compare two arrays, so you need to create a method to compare them. Most of the time, the
order of the words or numbers is fairly obviousbut for complicated objects, it becomes more
problematic.
User Defined Sorts
Here is the definition of a two-dimensional array we used earlier. This array stores Bobs three
products with a code, a description, and a price for each.
$products = array( array( “TIR”, “Tires”, 100 ),
array( “OIL”, “Oil”, 10 ),
array( “SPK”, “Spark Plugs”, 4 ) );
If we sort this array, what order will the values end up in? Because we know what the contents
represent, there are at least two useful orders. We might want the products sorted into alphabet-
ical order using the description or by numeric order by the price. Either result is possible, but
we need to use the function usort() and tell PHP how to compare the items. To do this, we
need to write our own comparison function.
Using PHP
P
ART I
80
05 7842 CH03 3/6/01 3:42 PM Page 80