php · level 3 · unit 3 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
picks one result from a list, using strict === checks.
A long if and elseif chain that only picks a value is noisy. match does it in one go. It compares a value against each , top to bottom, and the whole match becomes the result of the first arm that fits. Store it, echo it or return it.
It compares with ===, so "1" never matches 1. One arm can list several values with commas, and default catches everything else. With no default and no fitting arm, PHP throws an instead of quietly carrying on.
match (true) checks conditions instead: the first arm whose condition is true wins.
<?php
enum Light { case Red; case Amber; case Green; }
function advice(Light $light): string {
return match ($light) {
Light::Red, Light::Amber => "Stop",
Light::Green => "Go",
};
}
$age = 15;
$ticket = match (true) {
$age < 12 => "child",
$age < 18 => "teen",
default => "adult",
};
echo advice(Light::Amber) . ", one $ticket ticket\n"; A match over an enum that lists every case needs no default.
guess first
A form sends a rating of 5. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
$_POST["rating"] = "5";
$verdict = match ($_POST["rating"]) {
5 => "Brilliant",
4 => "Good",
default => "Thanks for the feedback",
};
echo "$verdict\n";
your turn
Your turn. Mark the spelling test.
Type a mark for a B somewhere between 50 and 60, then type a kind message for anyone below 40. Run it to grade all four scores.
fix it
A parcel to Japan breaks the delivery page. Fix it.
- Two countries work, then an
UnhandledMatchErrorsaysUnhandled match case 'Japan'. Which arm should catch Japan? - No arm lists Japan, and nothing catches the rest of the world. Everywhere else takes 10 days.
- After the France and Spain arm, add
default => "10 days",, then run it.
nailed it
you swapped long chains for one match. :D
matchhands back the result of the first arm that fits.- It compares with
===, so the types must match too. - No fitting arm and no
defaultthrows anUnhandledMatchError.
new words in your collection
- match
- arm
- UnhandledMatchError
This lesson isn’t saved. A free account remembers every lesson you finish.