Match Construct in PHP
In PHP 8.0
, a special construct
match
appeared, representing a simplified
version of switch
. This construct is also
used to select one value
from a series of values. Here is its syntax:
<?php
match (variable) {
value1 => result1,
value2 => result3,
value3 => result3,
default => default value
}
?>
What comes after the =>
operator
is returned as the result of the
match
operation and can be assigned
to a variable. Let's try it
in practice:
<?php
$lang = 'ru';
$res = match ($lang) {
'ru' => '111',
'en' => '222',
'de' => '333',
default => 'unsupported language'
};
echo $res;
?>
The variable $num
can take values
1
, 2
, 3
or 4
.
Determine which season the value
of this variable falls into.