php · level 2 · unit 2 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
sorts by any rule you can write.
sort only knows smallest first. To sort records by price, or words by length, you write the rule. usort hands your callback two items at a time, $a and $b, and asks which one goes first.
The , <=>, answers that for you. $a <=> $b gives -1 when $a is smaller, 0 when they match, and 1 when $a is bigger. Smaller things go first.
To flip the order, swap the sides: $b <=> $a puts the biggest first. Like sort, usort sorts in place.
<?php
$toys = [
["name" => "kite", "price" => 12],
["name" => "yo-yo", "price" => 3],
["name" => "robot", "price" => 25],
];
usort($toys, fn($a, $b) => $a["price"] <=> $b["price"]);
foreach ($toys as $toy) {
echo "{$toy["name"]}: £{$toy["price"]}\n";
} This arrow function takes two parameters, $a and $b, with a comma between them.
guess first
Sorting fruit by length. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
$fruit = ["banana", "fig", "apple"];
usort($fruit, fn($a, $b) => strlen($b) <=> strlen($a));
echo implode(", ", $fruit) . "\n";
your turn
Your turn. Rank the runners.
Sort the runners by time or by name. Type the same key, time or name, in both blanks, then run it.
fix it
Ben scored the most, but Cat wins. Can you fix it?
- The winner is whoever ends up first. Which order is the list sorted in right now?
$a <=> $bputs the smallest score first. You want the biggest first.- Swap the sides on line 7 so it says
$b["score"] <=> $a["score"], then press run.
nailed it
you can sort by any rule you like. :D
usorthands your callback two items to compare.$a <=> $bgives -1, 0 or 1, smallest first.- Swap the sides,
$b <=> $a, for biggest first.
new words in your collection
- usort
- spaceship operator
This lesson isn’t saved. A free account remembers every lesson you finish.