Categories
Uncategorized

Sorting Arrays Using A Custom Order

PHP comes with several sorting functions that will handle most use cases, however sometimes you need to sort a list of items in some non trivial way. This can often be the case when sorting objects.

Say for example you had a list of movies with an associated rating, something like:

class Movie {
    function __construct(string $name, int $rating)
    {
        $this->name = $name;
        $this->rating = $rating;
    }
}

$movies = [,
    new Movie('Jumanji', 5),
    new Movie('Paul', 3)
    new Movie('Platoon', 4)
];

To sort the list by the rating property, you can use usort:

usort(
    $movies,
    function ($one_movie, $another_movie) {
        return $one_movie->rating <=> $another_movie->rating;
    }
);

usort takes the array you are trying to sort, and a function that takes two of the items in the array and compares them. If the function returns less than zero, the first item comes before the second; greater than zero, the first item comes after the second. If the function returns zero, the two items are not ordered.

The function you give to usort can use as many checks as you need to determine an order:

usort(
    $movies,
    function ($one_movie, $another_movie) {
        // Order first by rating, then by name
        if ($one_movie->rating != $another_movie->rating) {
            return $one_movie->rating <=> $another_movie->rating;      
        }

        return $one_movie->name <=> $another_movie->name;
    }
);

Now your $movies will be ordered by descending rating, with matching rated movies being sorted by title.

Your email will not be given to anyone else, ever.