What are the difference between PHP 8 Match expression vs PHP 7 switch case?
PHP 8 Match expression code
echo match (8.0) {
'8.0' => "Oh no!",
8.0 => "This is what I expected",
};
//> This is what I expected
PHP 7 switch code
switch (8.0) {
case '8.0':
$result = "Oh no!";
break;
case 8.0:
$result = "This is what I expected";
break;
}
echo $result;
//> Oh no!
- Which one give better performance?
- Use case of match and switch.
Answer
Solution:
Main differences:
- match is an expression, while switch is statement
- match uses strict comparison, while switch uses loose
- match evaluates only one value, while switch may evaluate more (depending on break statement)
- match allows only single-line expression, while switch allows block of statements
Match expression has got already its page in the PHP documentation if you want to know more: https://www.php.net/manual/en/control-structures.match.php
SourceThe match expression branches evaluation based on an identity check of a value. Similarly to a switch statement, a match expression has a subject expression that is compared against multiple alternatives. Unlike switch, it will evaluate to a value much like ternary expressions. Unlike switch, the comparison is an identity check (===) rather than a weak equality check (==). Match expressions are available as of PHP 8.0.0.