The PHP switch statement compares a single expression against multiple case values and executes the matching block. In PHP 8, the newer match expression provides a stricter, shorter alternative when each branch returns a value.
switch Statement with breakInclude break; at the end of every case block unless you intentionally want execution to fall through to the next case. Always add a default: branch to handle unexpected inputs safely.
<?php
declare(strict_types=1);
$httpMethod = "POST";
switch ($httpMethod) {
case "GET":
echo "Fetching resource records..." . PHP_EOL;
break;
case "POST":
echo "Creating a new resource..." . PHP_EOL;
break;
case "PUT":
case "PATCH":
echo "Updating an existing resource..." . PHP_EOL;
break;
default:
echo "Method not supported." . PHP_EOL;
break;
}
Grouping case "PUT": and case "PATCH": together without a break between them lets two inputs share one handler cleanly.
match ExpressionUnlike switch, which uses loose equality (==) and requires break, match uses strict comparison (===), returns a value directly, and throws an UnhandledMatchError if no arm matches.
<?php
declare(strict_types=1);
$statusCode = 404;
$message = match ($statusCode) {
200, 201 => "Request succeeded",
400 => "Bad request payload",
401, 403 => "Authentication or permission error",
404 => "Resource not found",
default => "Unexpected server status",
};
echo $message . PHP_EOL;
break in switch: Without break, PHP continues executing every following case block until it hits a break or the closing brace.switch loose equality with 0 or "": switch (0) loosely matches case "guest": in older PHP versions or unexpected numeric strings. Use match for strict type checks.continue inside a switch inside a loop: In PHP, continue inside switch acts like break for the switch and triggers a warning. Use continue 2 to skip to the next loop iteration.switch or match in PHP 8?Use match whenever you are mapping an input value directly to a result or function call. Use switch when a branch needs several multi-line statements.
match need a break statement?No. match evaluates only the first matching arm and automatically stops without falling through.
match condition matches and there is no default?PHP throws an UnhandledMatchError exception, which helps catch missing enum or status cases during testing.
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.