Switch to Match

6 January, 2021

PHP 8 introduces the match expression, a different take on the switch statement.

Let's compare.

SWITCH MATCH
switch ($name) {
    case 'Golden retriever':
        $animal = 'dog';
        break;
    case 'Maine Coon':
        $animal = 'cat';
        break;
    case 'Grizzly':
    case 'Kodiak':
        $animal = 'bear';
        break;
    case 'Developer':
        $animal = 'wizard';
    default:
        $message = 'unknown';
        break;
}

 

$animal = match ($name) {
    'Golden retriever' => 'dog',
    'Maine Coon' => 'cat',
    'Grizzly', 'Kodiak' => 'bear',
    'Developer' => 'wizard'
    default => 'unknown',
};

 

 

Login or Register to Comment!