The usort function sorts an array by values where the values are sorted by a user-defined function. usort has the following syntax
bool usort ( array &$array , callback $cmp_function )
The comparison function takes two arguments and it must return integer values, either 0, positive integer, or negative integer.
- negative integer = first argument is smaller than the second
- zero = both arguments are equal
- positive integer = first argument is greater than the second
usort assigns new key for each element in the array. To preserve keys, use another sort function. The bool returns TRUE or FALSE to indicate whether the function succeeded or failed.
A simple example:
function cmp($a, $b)
{
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
$a = array(3, 2, 5, 6, 1);
print_r($a);
usort($a, "cmp");
print_r($a);
If your comparison function is inside a class you would need to call it as follows:
usort($a, array($this,"cmp");
Otherwise you would get an Invalid Comparison Function error.