match: a cleaner switch
match returns a value, compares strictly and throws if nothing matches (PHP 8+).
PHP · match: a cleaner switchBeginner
function statusLabel(int $code): string
{
return match (true) {
$code >= 500 => 'Server error',
$code >= 400 => 'Client error',
$code >= 300 => 'Redirect',
$code >= 200 => 'OK',
default => 'Unknown',
};
}
$role = 'editor';
echo match ($role) {
'admin', 'owner' => 'Full access',
'editor' => 'Can edit',
default => 'Read only',
};matchswitchphp8