Search code examples
phparrayssortingcustom-function

Sort array elements based on their return value from a custom function call


Is there a way to sort a PHP array by return value of a custom function? Like Python's sorted(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 calls keyfn (which can be slow) much more often than needed. Is there a more performant approach?


Solution

  • I ended up implementing it this way:

    function sort_by($key_f, $arr) {
        $values = array_map($key_f, $arr);
        asort($values);
        $sorted_arr = array();
    
        foreach ($values as $idx => $value) {
            $sorted_arr[] = $arr[$idx];
        }
    
        return $sorted_arr;
    }