×

php · level 3 · unit 3 · 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

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.