returnphp-8usortspaceship-operator

Deprecated Functionality: usort(): Returning bool from comparison function is deprecated, return an integer less than, equal to, or greater than zero


Ran into a slight issue here below with some of my code.

// sorting
$sortField = $this->sortField;
$sortDir = $this->sortDir;
usort($data, function ($a, $b) use ($sortField, $sortDir) {
    if ($sortDir == "asc") {
        return $a[$sortField] > $b[$sortField];
    } else {
        return $a[$sortField] < $b[$sortField];
    }
});

A bit confused here on what i need to change.

I read this in another thread.

PHP 8 introduced the Stable Sorting RFC, which (as it sounds) means that all sorting functions in PHP are now "stable".

The spaceship operator is used for comparing two expressions. It returns -1, 0 or 1 when $a is respectively less than, equal to, or greater than $b. Comparisons are performed according to PHP's usual type comparison rules.

So does this mean I need to add the spaceship operator here in the returns:

        return $a[$sortField] <=> $b[$sortField];
    } else {
        return $a[$sortField] <=> $b[$sortField];
    }

That is it?


Solution

  • I, personally, haven't used that operator, but yeah since you need the return to be 1, 0, or -1. But you will want to reverse the left and right so it behaves correctly based on sort order. Like so:

    if ($sortDir == "asc") {
        return $a[$sortField] <=> $b[$sortField];
    } else {
        return $b[$sortField] <=> $a[$sortField];
    }
    

    I just got this error on an older website with the error stating the functionality was "deprecated" Ha! It caused the api call to fail completely, so I think we are past "deprecated", don't ya think? :-)

    Also, I may have your logic backwards, but I think you should get the drift.

    Hope that helps.