usort
bool usort(array array, string func)
|
array
|
Array to sort using the supplied function
|
|
func
|
Function to use to sort the array
|
Sorts the given scalar array with a user-defined function.
Returns:
TRUE on success; FALSE on error
Description:
usort() sorts array
according to the user-defined function named by func
. This can be useful for doing sorts with custom algorithms or doing non-case-sensitive sorts with alphabetic characters. When you pass usort() an array and the name of a user-defined function, it uses the bubblesort method and traverses the elements of the array to sort them. The custom function must return -1, 0, or 1 for this method to work correctly (see example). If used on an associative array, this function causes the keys to be destroyed while sorting on the values.
func
should be written to accept two parameters, which it compares. If they're considered equivalent, 0 should be returned. If the first is considered to be greater, 1 should be returned. If the second is considered to be greater, -1 should be returned.
Version:
PHP 3 since 3.0.3, PHP 4
See also:
array_multisort()
arsort()
asort()
krsort()
ksort()
natsort()
natcasesort()
rsort()
sort()
uasort()
uksort()
Example:
Sort an array using a user-defined comparison function
function usort_cmp($a, $b) {
if ($a == $b) return 0;
return ($a > $b) ? -1 : 1;
}
$arr = array("Banana", "carrot",
"Apple", "banana",
"apple", "Carrot");
usort($arr, "usort_cmp");
while(list($k, $v) = each($arr)) {
echo "$k => $v\n";
}
Output:
0 => Apple
1 => Banana
2 => Carrot
3 => apple
4 => banana
5 => carrot
|