×

php · level 2 · unit 2 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.