Page 168 - Open Soource Technologies 304.indd
P. 168
Web Technologies-I
Notes Our compare() function takes two, one called x and one called y. The purpose of this function
is to take two values and determine their order.
For this example, the x and y parameters will be two of the arrays within the main array, each
representing one product. To access the Description of the array x, we type $x[1] because the
Description is the second element in these arrays, and numbering starts at zero. We use $x[1]
and $y[1] to compare the Descriptions from the arrays passed into the function.
When a function ends, it can give a reply to the code that called it. This is called returning a
value. To return a value, we use the keyword return in our function. For example, the line return
1; sends the value 1 back to the code that called the function.
To be used by usort(), the compare() function must compare x and y. The function must return
0 if x equals y, a negative number if it is less, and a positive number if it is greater. Our function
w ill return 0, 1, or –1, depending on the values of x and y.
The final line of code calls the built-in function usort() with the array we want sorted ($products)
and the name of our comparison function (compare()).
If we want the array sorted into another order, we can simply write a different comparison
function. To sort by price, we need to look at the third column in the array, and create this
comparison function:
function compare($x, $y)
{
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.
7.5.2 Reverse User Sorts
The functions sort(), asort(), and ksort() all have a matching reverse sort with an “r” in the function
name. You provide the comparison function, so write a comparison 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,
162 LOVELY PROFESSIONAL UNIVERSITY