usort
Sort an array by values using a user-defined comparison function
&reftitle.description;
boolusort
arrayarray
callablecmp_function
This function will sort an array by its values using a user-supplied
comparison function. If the array you wish to sort needs to be sorted by
some non-trivial criteria, you should use this function.
If two members compare as equal, their relative order in the sorted array is undefined.
¬e.no-key-association;
&reftitle.parameters;
array
The input array.
cmp_function
&return.callbacksort;
&callback.cmp;
&reftitle.returnvalues;
&return.success;
&reftitle.changelog;
&Version;
&Description;
4.1.0
A new sort algorithm was introduced. The cmp_function
doesn't keep the original order for elements comparing as equal.
&reftitle.examples;
usort example
$value) {
echo "$key: $value\n";
}
?>
]]>
&example.outputs;
Obviously in this trivial case the sort
function would be more appropriate.
usort example using multi-dimensional array
]]>
When sorting a multi-dimensional array, $a and
$b contain references to the first index of the array.
&example.outputs;
usort example using a member function of an object
name = $name;
}
/* This is the static comparing function: */
static function cmp_obj($a, $b)
{
$al = strtolower($a->name);
$bl = strtolower($b->name);
if ($al == $bl) {
return 0;
}
return ($al > $bl) ? +1 : -1;
}
}
$a[] = new TestObj("c");
$a[] = new TestObj("b");
$a[] = new TestObj("d");
usort($a, array("TestObj", "cmp_obj"));
foreach ($a as $item) {
echo $item->name . "\n";
}
?>
]]>
&example.outputs;
&reftitle.seealso;
uasort
&seealso.array.sorting;