php - Sort array elements based on their return value from a custom function call
504
Is there a way to sort a PHP array by return value of a custom function? Like Python'ssorted(arr, key=keyfn)
or Clojure's(sort-by keyfn arr)
,
usort($array, function ($a, $b) {
$key_a = keyfn($a);
$key_b = keyfn($b);
if ($key_a == $key_b) return 0;
if ($key_a < $key_b) return -1;
return 1;
});
The above does what I want, but it's verbose and it callskeyfn
(which can be slow) much more often than needed. Is there a more performant approach?
Answer
Solution:
Some simple code for caching results of
predicate
and sorting (usingspaceship
operator which reduces lines where you return 0,1,-1). In case ofpredicate
result asint
you can even return$key_a - $key_b
:Simple fiddle https://3v4l.org/W1N7Y
Answer
Solution:
I ended up implementing it this way:
Answer
Solution:
From PHP7.4 and higher you can modernize/refine @u_mulder's snippet using the null coalescing assignment operator as the following.
Code: (Demo)
Alternatively, making mapped calls of your custom function will be more concise, but will result in a greater number of custom function calls. (Demo)
This can be prevented in a classic loop, again with the null coalescing operator, but it may be a little harder to conceptualize with the double-assignment line. (Demo)