Is there a simple usort in PHP?

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?

+5
source share
2 answers

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

No.

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

The language should be designed in such a way as to provide common tools to achieve the goal without providing many functions to serve certain use cases that may or may not be popular if this effectiveness does not adversely affect such a decision.

+2
source

The simple answer is: since no one asked for it, and no one implemented it.

PHP is managed by people who have a patch or people who motivate others to write a patch. If a function is hardly interesting to anyone, it is not requested or executed.

I believe that the function you want is too specific, and the gain is too small.

But if you want it: add a function request via bugs.php.net or offer a patch via github.

0
source

Source: https://habr.com/ru/post/1236932/


All Articles