The match expression

match expressions are available as of PHP 8.0.0

$food = 'cake';

$result = match ($food) {
    'apple' => 'This food is an apple',
    'bar' => 'This food is a bar',
    'cake' => 'This food is a cake',
};

var_dump($result);
// string(19) "This food is a cake"
$result = match ($condition) {
    1, 2 => foo(),
    3, 4 => bar(),
    default => baz(),
};
$age = 23;

$result = match (true) {
    $age >= 65 => 'senior',
    $age >= 25 => 'adult',
    $age >= 18 => 'young adult',
    default => 'kid',
};

var_dump($result);
// string(11) "young adult"

Unlike switch, the comparison is an identity check (===) rather than a weak equality check (==).


https://www.php.net/manual/en/control-structures.match.php
This site uses cookies.