How does the usort function in PHP compare to custom array sorting methods?
The usort function in PHP allows for custom sorting of an array based on a user-defined comparison function. This function can be used to sort arrays in ways that the built-in sorting functions cannot achieve. By providing a custom comparison function, usort gives developers more flexibility and control over the sorting process.
// Example of using usort to sort an array of numbers in descending order
$numbers = [5, 2, 8, 1, 9];
usort($numbers, function($a, $b) {
if ($a == $b) {
return 0;
}
return ($a > $b) ? -1 : 1;
});
print_r($numbers);