简体   繁体   中英

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?

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.

Simple answer: Since nobody requested it and nobody implemented it.

PHP is driven by people having a patch or people motivating others to write a patch. If a feature is hardly interesting for anybody it isn't requested and isn't implemented.

I believe the feature you want is too specific and the gain is too small.

But if you want it: Add a feature request via bugs.php.net or propose a patch via github.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM