PHP

Sorting with user-defined element comparison

The sorting functions described so far in this section sort elements in alphabetic, numeric, or alphanumeric order. To sort elements based on user-defined criteria, PHP provides three functions:

usort(array subject, string compare_function)
uasort(array subject, string compare_function)
uksort(array subject, string compare_function)

usort( ) sorts the subject array based on the value of each element, uasort( ) preserves the key/value associations as described earlier for the asort( ) function, and uksort( ) rearranges the elements based on the key of each element. When these functions sort the subject array, the user-defined compare function is called to determine if one element is greater than, lesser than, or equal to another. The compare function can be written to implement any sort order, but the function must conform to the prototype:

integer my_compare_function(mixed a, mixed b)

We discuss how to write functions in more detail in Section 2.10. The compare function takes two arguments, a and b, and returns -1 if a is less than b, 1 if a is greater than b, and 0 if a and b are equal. How the function determines that one value is less than, greater than, or equal to another depends on the requirements of sorting. The following example shows how usort( ) sorts an array of strings based on the length of each string:

// Compare two string values based on the length
function cmp_length($a, $b)
{
  if (strlen($a) < strlen($b)) return -1;
  if (strlen($a) > strlen($b)) return 1;
  // String lengths must be equal
  return 0;
}
$animals =
  array("cow", "ox", " hippopotamus", "platypus");
usort($animals, "cmp_length");
print_r($animals);

The array $animals is printed:

Array ([0]=>ox [1]=>cow [2]=>platypus [3]=>hippopotamus)

In this example, cmp_length( ) is defined as the compare function, but it isn't called directly by the script. The name of the function, "cmp_length", is passed as an argument to usort( ), and usort( ) uses cmp_length( ) as part of the sorting algorithm. User-defined functions used in this way are often referred to as callback functions.

PHP has several library functions that allow user-defined behavior through user-defined callback functions. The array_map( ) and array_walk( ) functions allow user-defined functions to be applied to the elements of an array. We provide another example in Appendix D where we implement user-defined session management.

by BrainBellupdated
Advertisement: