PHP » Arrays » usort()

Syntax:
bool usort (array array, string compare_func)
array
Array to be sorted.
compare_func
Function that compares two elements.

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.

Examples

Code:
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, ";
}

?>
Output:
Michael Johnson, John Jones, Matthew Smith, Christian Williams
Explanation:

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.

See Also: