switch Statements & PHP 8 match ExpressionsThe switch statement executes different blocks of code based on matching an expression against multiple potential values. Starting in PHP 8.0, the match expression provides a modern, strictly-typed, expression-returning alternative to switch.
switch vs PHP 8 match Expression| Feature | switch Statement |
PHP 8 match Expression |
|---|---|---|
| Comparison Type | Loose equality (==) |
Strict equality (===) |
| Return Behavior | Statement block (Requires break) |
Returns a value directly |
| Fallthrough | Falls through to next case unless break is present |
No fallthrough; executes matching arm only |
| Exhaustive Matching | Ignores unmatched values unless default is set |
Throws UnhandledMatchError if unmatched |
flowchart TD
A["Input Subject Value"] --> B["PHP 8 match(value)"]
B --> C{"Arm 1 (Strict ===)"} -- Match --> D["Return Arm 1 Value"]
B --> E{"Arm 2 (Strict ===)"} -- Match --> F["Return Arm 2 Value"]
B --> G{"Default Arm"} -- Match --> H["Return Default Value"]
<?php
declare(strict_types=1);
// Modern PHP 8 match expression example
function getHTTPStatusMessage(int $statusCode): string
{
return match ($statusCode) {
200, 201 => "Success: Request completed successfully.",
400 => "Client Error: Bad Request payload.",
401, 403 => "Security Error: Unauthorized or Forbidden access.",
404 => "Not Found: Resource does not exist.",
500, 502, 503 => "Server Error: Internal system failure.",
default => "Unknown HTTP Response Code ($statusCode)",
};
}
// Legacy switch statement comparison
$userRole = 'editor';
$permissions = [];
switch ($userRole) {
case 'admin':
$permissions[] = 'manage_users';
// fallthrough intentional
case 'editor':
$permissions[] = 'publish_articles';
$permissions[] = 'edit_content';
break;
default:
$permissions[] = 'read_content';
break;
}
echo getHTTPStatusMessage(404) . "
";
echo "Editor Permissions: " . implode(", ", $permissions) . "
";
match over switch in PHP 8+: match is safer due to strict === type checking and eliminates accidental break; omission bugs.default Arm in match: Prevents unexpected UnhandledMatchError exceptions when unexpected input is passed.200, 201 => ... in match arms to avoid redundant case definitions.Refactor a switch statement checking $dayName ('Monday', 'Tuesday', etc.) into a modern PHP 8 match expression returning "Weekday" or "Weekend"!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.