Library contents

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

  1. Start with B and A with equal scores
  2. Do this Sort by score, then by name
  3. Result A, B
The second comparison resolves the tie in alphabetical order.

Syntax

PHP 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.

From the programdeclare(strict_types=1)
First output lineAda
lesson.php
<?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";
}
Output
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

Advertisements

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?

Given6 · 2 · 6 · 0
Worked result0 · 2 · 6 · 6

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?

Given3 · 0 · 8 · 3
Worked result0 · 3 · 3 · 8