How is the usort function used in PHP?
The usort function is a sorting function in PHP, used to custom sort arrays.
Function prototype: bool usort (array &$array, callable $cmp_function)
Explanation of parameters:
- $array: the array that needs to be sorted must be passed by reference.
- $cmp_function: Comparison function used to determine the order between elements. The comparison function must return an integer, with a negative number if the first parameter is less than the second, a positive number if the first parameter is greater than the second, and 0 if the two parameters are equal.
Return value: true for success, false for failure.
“你做错了” → “You made a mistake”
$numbers = [4, 2, 8, 6];
usort($numbers, function($a, $b) {
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
});
print_r($numbers);
The output is an array with elements 2, 4, 6, and 8.
In the example above, the array $numbers is sorted using the usort function. The comparison function uses a simple logic to determine the order between elements, returning -1 if the first parameter is smaller than the second, and 1 otherwise. Finally, the array is reordered in ascending order.