PHP — Switch statements and match expressions
PHP 8 match selects a result using strict comparisons and supports several case values in one arm. A switch statement instead uses loose comparison and allows fall-through.
A simple example
Match one case
- Start with Value 2
- Do this Match case 2
- Result two
<?php
echo match (2) {
2 => "two",
default => "other",
}, PHP_EOL;
two
Route several event states to one action
Map queued and retry to the same pending action. A sent event is complete, and an unrecognized state is sent for review. Use match when the operation is a mapping to a value. The equivalent switch below ends each action with return. With these known string inputs both dispatchers must agree.
A parcel dashboard receives status updates. A queued parcel and a parcel awaiting retry both belong in the pending tray. Mark a sent parcel done and send unfamiliar statuses for review.
Run the example
Use PHP 8.2 or later. Run these commands from the directory containing the example.
php lesson.php
<?php
declare(strict_types=1);
function routeWithSwitch(string $state): string {
switch ($state) {
case 'queued':
case 'retry':
return 'pending';
case 'sent':
return 'done';
default:
return 'review';
}
}
foreach (['queued', 'retry', 'sent', 'unknown'] as $state) {
$action = match ($state) {
'queued', 'retry' => 'pending',
'sent' => 'done',
default => 'review',
};
if ($action !== routeWithSwitch($state)) throw new LogicException('Routes disagree');
echo $action . "\n";
}
pending pending done review
Both pending states share one result. The other branches distinguish a known completion from a new or misspelled status.
Try it yourself
What should an unrecognized state such as paused produce?
Check your answer
It produces review. Add an explicit case when the application defines how to handle that state.