The match Construct
The match construct was introduced in PHP 8.0 and provides a more concise and safer way of branching compared to switch. It takes an expression for comparison and returns the value of the first matching condition. Unlike switch, match performs strict comparison (===) and does not require break.
Syntax
$result = match ($value) {
condition1 => result1,
condition2 => result2,
...
default => default_result
};
Example
Simple number matching:
<?php
$res = match (2) {
1 => 'One',
2 => 'Two',
3 => 'Three',
default => 'Unknown'
};
echo $res;
?>
Code execution result:
'Two'
Example
Matching with multiple conditions:
<?php
$age = 25;
$res = match (true) {
$age < 18 => 'Child',
$age >= 18 && $age < 65 => 'Adult',
$age >= 65 => 'Senior'
};
echo $res;
?>
Code execution result:
'Adult'
Example
Usage with arrays:
<?php
$arr = [1, 2, 3];
$res = match ($arr) {
[1, 2, 3] => 'First sequence',
[4, 5, 6] => 'Second sequence',
default => 'Other sequence'
};
echo $res;
?>
Code execution result:
'First sequence'