PHP 8 introduced a new feature called match
expression, which is similar to the switch
statement but with some key differences and improvements. This post will explain the differences between switch
and match
and provide examples to illustrate their usage.
For more details, you can refer to the official PHP documentation.
switch
and match
Differences between - Return Value: The
match
expression returns a value, whereas theswitch
statement does not. - Strict Comparison:
match
uses strict comparison (===
), whileswitch
uses loose comparison (==
). - No Fall-through:
match
does not allow fall-through, which means each case must be unique and there is no need forbreak
statements. - Expression-based:
match
is an expression and can be used in assignments, whileswitch
is a statement.
Example 1: Basic Usage
switch
Using $input = 2;
$result = '';
switch ($input) {
case 1:
$result = 'One';
break;
case 2:
$result = 'Two';
break;
case 3:
$result = 'Three';
break;
default:
$result = 'Unknown';
break;
}
echo $result; // Outputs: Two
match
Using $input = 2;
$result = match ($input) {
1 => 'One',
2 => 'Two',
3 => 'Three',
default => 'Unknown',
};
echo $result; // Outputs: Two
Example 2: Type Safety
switch
Using <?php
$input = '2';
$result = '';
switch ($input) {
case 1:
$result = 'One';
break;
case 2:
$result = 'Two';
break;
case 3:
$result = 'Three';
break;
default:
$result = 'Unknown';
break;
}
echo $result; // Outputs: Two (loose comparison)
match
Using <?php
$input = '2';
$result = match ($input) {
1 => 'One',
2 => 'Two',
3 => 'Three',
default => 'Unknown',
};
echo $result; // Outputs: Unknown (strict comparison)
As you can see, the match expression provides a more concise and safer way to handle conditional logic compared to the switch statement. It ensures strict type comparisons and eliminates the risk of fall-through errors.
By understanding and utilizing the match expression, you can write cleaner and more predictable code in PHP 8 and beyond.