PHP 8 interview question · Most asked

How does `match` differ from `switch`?

Summary

match is an expression that returns a value, uses strict (===) comparison, has no fall-through, and throws UnhandledMatchError if no arm matches.

Longer Answer

switch is a statement with loose comparison (==) and implicit fall-through, which is a frequent bug source. match fixes all three: each arm is a single expression, comparison is strict, and missing cases fail loudly instead of silently doing nothing.

Arms can have comma-separated conditions, and match (true) is a common idiom for range checks.

Code Example

<?php
$status = 404;

$message = match (true) {
    $status >= 500 => 'Server error',
    $status === 404, $status === 410 => 'Not found',
    $status >= 400 => 'Client error',
    default => 'OK',
};

echo $message; // Not found

Key Points

  • Expression: assign or return its result
  • Strict comparison (===)
  • No fall-through, no break needed
  • Unmatched value throws UnhandledMatchError
  • Arms are single expressions (use a function for multi-statement logic)

Comparison / Tradeoffs

Aspect switch match
Kind Statement Expression
Comparison Loose == Strict ===
Fall-through Yes (needs break) No
No match Silently skipped UnhandledMatchError

Explanation

What interviewers look for

All four differences (expression, strict, no fall-through, exhaustiveness error) and the match(true) idiom.

Follow-up questions

  • How would you use match with enums?

More most-asked PHP 8 questions

← All PHP 8 questions