In PHP, the usort function takes two arguments: an array to sort and a callback. The callback also takes two arguments: $ a and $ b. Then we compare the two as we want. This always surprises me, because this use case is not too common for usort . Usually we sort the values by the same property or use the same logic for $ a and $ b. For example, if we want to sort by length:
$animals = ['dog', 'tiger', 'giraffe', 'bear']; usort($animals, function ($a, $b) { return strlen($a) - strlen($b); });
This will work, but we have to say strlen twice. It would be better to say this:
usort($animals, function ($element) { return strlen($element); });
Or even like this:
usort($animals, 'strlen');
I wrote this function myself (using PHP 7, but it can be easily changed to PHP 5):
function simple_usort(array &$array, callable $callback): bool { return usort($array, function ($a, $b) use ($callback) { return $callback($a) <=> $callback($b); }); }
It works fine, but isn't it built on PHP already in some other function? If not, why doesn't PHP support this very popular and convenient sorting method?
source share