PHP usort and the spaceship operator
usort sorts an array in place with a three-way comparator and reindexes its elements with integer keys.
A simple example
usort and the spaceship operator
- Start with B and A with equal scores
- Do this Sort by score, then by name
- Result A, B
Syntax
usort($rows, $compare)
Run this example in PHP
Save the program as lesson.php. Use PHP 8.2 or later.
php lesson.php
Rank scores with an explicit tie rule
A queue or leaderboard contains entries with equal primary scores. Specify how ties are handled so the final ordering is predictable and preserves arrival order when the task requires it.
<?php
declare(strict_types=1);
$rows = [['Bea', 8], ['Cam', 5], ['Ada', 8]];
usort($rows, static function (array $a, array $b): int {
return ($b[1] <=> $a[1]) ?: ($a[0] <=> $b[0]);
});
foreach ($rows as [$name, $score]) {
echo $name . "\n";
}
Ada Bea Cam
Use the spaceship operator with reversed scores for descending order. If two scores tie, compare the names in ascending order. Use uasort when associative keys carry meaning.
PHP documentation for usort and the spaceship operator
Count packs on the delivery slip
A loading desk receives four item counts in sequence. The supervisor sorts the counts from smallest to largest. Which sequence goes on the summary sheet?
Review print quantities
A print room records four job quantities, including a cancelled job. The supervisor sorts the counts from smallest to largest. Which sequence goes on the summary sheet?