简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM