Possible to pass a closure to usort in PHP?

  • When defining closures, you can use the use keyword to let the function "see" a certain variable (or variables). See also the PHP documentation about Anonymous functions.

Closures may also inherit variables from the parent scope. Any such variables must be declared in the function header. Inheriting variables from the parent scope is not the same as using global variables. Global variables exist in the global scope, which is the same no matter what function is executing. The parent scope of a closure is the function in which the closure was declared (not necessarily the function it was called from).

  • Please also note that defining a closure and assigning it to a variable is a normal assignment operation, so you will need the ; after the closing } of the closure.

After making these changes your code would look like this (and should work fine):

public function sortAscending($accounts, $key)
{
    $ascending = function($accountA, $accountB) use ($key) {
        if ($accountsA[$key] == $accountB[$key]) {
            return 0;
        }
        return ($accountA[$key] < $accountB[$key]) ? -1 : 1;
    };
    usort($accounts, $ascending);

    return $accounts;
}

To clarify this - and code it like a closure - and use the PHP7 spaceship operator - and correct a typo in line 4 of the first answer, skip the $ascending variable:

public function sortAscending($accounts, $key)
{
    usort($accounts, function($accA, $accB) use ($key) {
        return $accA[$key] <=> $accB[$key];
    });
    return $accounts;
}