usortSort an array by values using a user-defined comparison function
&reftitle.description;
boolusortarrayarraycallablevalue_compare_func
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.
¬e.sort-unstable;
¬e.no-key-association;
&reftitle.parameters;
array
The input array.
value_compare_func
&return.callbacksort;
&callback.cmp;
Returning non-integer values from the comparison
function, such as float, will result in an internal cast to
integer of the callback's return value. So values such as
0.99 and 0.1 will both be cast to an integer value of 0, which will
compare such values as equal.
&reftitle.returnvalues;
&return.success;
&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;
usort example using a closure
to sort a multi-dimensional array
'z', 'key_b' => 'c');
$array[1] = array('key_a' => 'x', 'key_b' => 'b');
$array[2] = array('key_a' => 'y', 'key_b' => 'a');
function build_sorter($key) {
return function ($a, $b) use ($key) {
return strnatcmp($a[$key], $b[$key]);
};
}
usort($array, build_sorter('key_b'));
foreach ($array as $item) {
echo $item['key_a'] . ', ' . $item['key_b'] . "\n";
}
?>
]]>
&example.outputs;
&reftitle.seealso;
uasort&seealso.array.sorting;