What are the difference between PHP 8 Match expression vs PHP 7 switch case?

8.7k views Asked by At

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!
  1. Which one give better performance?
  2. Use case of match and switch.
1

There are 1 answers

1
JSowa On

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

The 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.