Sorts an array using a user defined function.
The usort() function accepts an array and a compare function. The compare function should accept two parameters and return -1 if the first is smaller than the second, 0 if they are equal, and 1 if the first is bigger than the second. As of PHP 4.1.0, the sorting algorithm is not stable and can reorder equal elements.
function compare($a, $b)
{
$c = split(" ", $a);
$d = split(" ", $b);
if ($c[1] < $d[1])
return -1;
if ($c[1] > $d[1])
return 1;
return 0;
}
$names = array("Michael Johnson", "Christian Williams", "Matthew Smith", "John Jones");
usort($names, "compare");
foreach ($names as $name) {
print "$name, ";
}
?>
Michael Johnson, John Jones, Matthew Smith, Christian Williams
The compare function splits a name in the $names array into first and last name and compares the last names. Using the usort() function, the names are sorted by the last name.