Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there simple usort in PHP?

In PHP, usort function takes two arguments: array to sort and a callback. The callback takes two arguments as well: $a and $b. Then, we compare those two in any way we want. It always surprises me, because this use case for usort is not too common. We usually sort values by the same property or using the same logics for both $a and $b. For example, if we want to sort by the length:

$animals = ['dog', 'tiger', 'giraffe', 'bear'];

usort($animals, function ($a, $b) {
    return strlen($a) - strlen($b);
});

That will work, but we need to say strlen twice. It would be nicer to say it that way:

usort($animals, function ($element) {
    return strlen($element);
});

Or even like this:

usort($animals, 'strlen');

I have written this kind of function myself (using PHP 7 goodies, 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 perfectly, but isn't it built in PHP already in some other function? If not, why PHP doesn't support this very popular and convenient way of sorting?

like image 567
Robo Robok Avatar asked Oct 30 '22 14:10

Robo Robok


1 Answers

It works perfectly, but isn't it built in PHP already in some other function?

No.

If not, why PHP doesn't support this very popular and convenient way of sorting?

A language should be designed to provide generic tools to get things done without supplying a multitude of functions to cater for certain use cases that may or may not be popular, granted that performance isn't negatively impacted by such a decision.

like image 124
Ja͢ck Avatar answered Nov 15 '22 03:11

Ja͢ck