Specifications
if ( $x[2] == $y[2] )
return 0;
else if ( $x[2] < $y[2] )
return -1;
else
return 1;
}
When usort($products, compare) is called, the array will be placed in ascending order by
price.
The “u” in usort() stands for “user” because this function requires a user-defined comparison
function. The uasort() and uksort() versions of asort and ksort also require a user-defined
comparison function.
Similar to asort(), uasort() should be used when sorting an associative array by value. Use
asort if your values are simple numbers or text. Define a comparison function and use
uasort() if your values are more complicated objects such as arrays.
Similar to ksort(), uksort() should be used when sorting an associative array by key. Use
ksort if your keys are simple numbers or text. Define a comparison function and use uksort()
if your keys are more complicated objects such as arrays.
Reverse User Sorts
The functions sort(), asort(), and ksort() all have a matching reverse sort with an “r” in
the function name. The user-defined sorts do not have reverse variants, but you can sort a mul-
tidimensional array into reverse order. You provide the comparison function, so write a com-
parison function that returns the opposite values. To sort into reverse order, the function will
need to return 1 if x is less than y and –1 if x is greater than y. For example
function reverseCompare($x, $y)
{
if ( $x[2] == $y[2] )
return 0;
else if ( $x[2] < $y[2] )
return 1;
else
return -1;
}
Calling usort($products, reverseCompare) would now result in the array being placed in
descending order by price.
Using PHP
P
ART I
82
05 7842 CH03 3/6/01 3:42 PM Page 82