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.
Differences between switch and match
- Return Value: The
matchexpression returns a value, whereas theswitchstatement does not. - Strict Comparison:
matchuses strict comparison (===), whileswitchuses loose comparison (==). - No Fall-through:
matchdoes not allow fall-through, which means each case must be unique and there is no need forbreakstatements. - Expression-based:
matchis an expression and can be used in assignments, whileswitchis a statement.
Example 1: Basic Usage
Using switch
$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
Using match
$input = 2;
$result = match ($input) {
1 => 'One',
2 => 'Two',
3 => 'Three',
default => 'Unknown',
};
echo $result; // Outputs: Two
Example 2: Type Safety
Using switch
<?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)
Using match
<?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.