0% complete

Conditionals · Lesson 6 of 6

Match Expression

Return a value from strict match arms without fall-through.

Lesson

The match expression compares with identity, returns a value, and does not fall through. Every input must match an arm or a default, otherwise PHP throws an UnhandledMatchError. Use it when a choice naturally produces a value rather than a sequence of commands. Multiple alternatives can share one arm by separating values with commas. Further guidance Test each branch with a normal value, a boundary value, and an unexpected value. Order range checks from specific to broad, make the fallback behavior intentional, and keep related decisions readable. A condition should use validated data rather than an untrusted request value directly. Practice task: Create a fresh example for Match Expression. Predict the result before running it, then change one input and explain why the result changes. Test a normal case and one boundary or invalid case where it applies. Compare your output with the example and note one rule you would use in a real project.

Code examples

Match Expression
PHP
$status = 404;
$label = match ($status) {
    200 => 'OK',
    404, 410 => 'Not found',
    default => 'Other response',
};
echo $label;
Expected output
Not found

Key points

  • Return a value from strict match arms without fall-through.
  • Test boundary cases for every conditional branch.
  • Keep fallback behavior explicit and use validated values.

Your learning progress

Finish this lesson

Optional practice

PHP playground

This site does not execute learner-provided PHP code. Connect a secured PHP sandbox service before enabling code execution.

Execution is disabled. No code is sent to a server.