Custom sorting algorithm for array using PHP spaceship operator

The new spaceship operator introduced in PHP 7 can be used to compare two expressions. Here’s a little example showing a custom sorting function using usort which first orders the given array by name, then by category, alphabetically.

usort($mylist, function($a, $b) {
    if($a->category == $b->category) {
        return $a->name <=> $b->name;
    return $a->category <=> $b->category;

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *