Specifications
The following code sorts this array into alphabetical order using the second column in the
array—the description.
function compare($x, $y)
{
if ( $x[1] == $y[1] )
return 0;
else if ( $x[1] < $y[1] )
return -1;
else
return 1;
}
usort($products, compare);
So far in this book, we have called a number of the built-in PHP functions. To sort this array,
we have defined a function of our own. We will examine writing functions in detail in Chapter
5, “Reusing Code and Writing Functions,” but here is a brief introduction.
We define a function using the keyword function. We need to give the function a name.
Names should be meaningful, so we’ll call it compare(). Many functions take parameters or
arguments. 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 will 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)
{
Using Arrays
C
HAPTER 3
3
USING ARRAYS
81
05 7842 CH03 3/6/01 3:42 PM Page 81