Coding problem · Easy · Language Idioms
Leaderboard Sorting with usort and <=>
Easy Language practicals Seen at Booking.com, Automattic, Shopify
You receive players as associative arrays: ['name' => 'Ana', 'score' => 90, 'timeSec' => 61].
Return the player names ranked by:
scoredescending,- then
timeSecascending (faster wins ties), - then
nameascending.
Example 1
Input: players = [Ana 90 61, Bo 95 70, Cy 90 55] Output: ["Bo","Cy","Ana"]
Hints
Hint 1
usort with a comparator returning <=> of two arrays compares element by element.
Hint 2
Swap $a/$b on one side for descending order.
Write and run your solution
Loading the editor… (JavaScript is required to run code in your browser.)
Solution and explanation
Show the solution
Time O(n log n) · Space O(n)
The spaceship operator <=> compares arrays element by element, so [$b['score'], $a['timeSec'], $a['name']] <=> [$a['score'], $b['timeSec'], $b['name']] expresses "score descending, then time ascending, then name ascending" in one line. array_column then extracts the names.
Since PHP 8.0 usort is stable, but relying on an explicit final tie-breaker keeps results deterministic everywhere.
Reference solution
<?php
function rankPlayers(array $players): array
{
usort(
$players,
fn(array $a, array $b): int => [$b['score'], $a['timeSec'], $a['name']] <=> [$a['score'], $b['timeSec'], $b['name']]
);
return array_column($players, 'name');
}
Common mistakes
- Returning a boolean from the comparator (
$a > $b) — it must return an int. - Using
sort()on associative arrays and losing structure.
Follow-up questions
- Sort a list of objects with readonly properties instead of arrays.
- Rank with ties sharing a position (dense ranking).
More Language Idioms problems
- Type-safe groupBy<T, K>() · Easy
- Result Type Instead of Exceptions · Medium
- Typed pick() and omit() · Easy
- Slugify a Title (Strings & Regex) · Easy
- Order Status Enum with Transitions · Medium
- Lazy chunked() Generator · Easy