As well as being similar to a switch, match expressions can be thought of as enhanced lookup tables — for when a simple array lookup isn't enough without extra handling of edge cases, but a full switch statement would be overweight.
For a familiar example, the following
<?php
function days_in_month(string $month): int
{
static $lookup = [
'jan' => 31,
'feb' => 0,
'mar' => 31,
'apr' => 30,
'may' => 31,
'jun' => 30,
'jul' => 31,
'aug' => 31,
'sep' => 30,
'oct' => 31,
'nov' => 30,
'dec' => 31
];
$name = strtolower(substr($name, 0, 3));
if(isset($lookup[$name])) {
if($name == 'feb') {
return is_leap($year) ? 29 : 28;
} else {
return $lookup[$name];
}
}
throw new InvalidArgumentException("Bogus month");
}
?>
with the fiddly stuff at the end, can be replaced by
<?php
function days_in_month(string $month): int
{
return match(strtolower(substr($month, 0, 3))) {
'jan' => 31,
'feb' => is_leap($year) ? 29 : 28,
'mar' => 31,
'apr' => 30,
'may' => 31,
'jun' => 30,
'jul' => 31,
'aug' => 31,
'sep' => 30,
'oct' => 31,
'nov' => 30,
'dec' => 31,
default => throw new InvalidArgumentException("Bogus month"),
};
}
?>
Which also takes advantage of "throw" being handled as of PHP 8.0 as an expression instead of a statement.