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
breakneeded - 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
matchwith enums?
More most-asked PHP 8 questions
- How should passwords be stored in PHP?
- What are the most important features introduced in PHP 8.0?
- What are union types in PHP 8 and how do you use them?
- What are named arguments and what are their benefits and risks?
- What is constructor property promotion?
- What happens to an HTTP request in a PHP-FPM application, and what does 'shared nothing' mean?
- What are enums in PHP 8.1? Explain pure vs backed enums.
- Explain readonly properties (8.1) and readonly classes (8.2).