PHP8 Match Expression

The new match is similar to switch and has the following features:

Match is an expression, meaning its result can be stored in a variable or returned.

Match branches only support single-line expressions and do not need a break; statement.

Match does strict comparisons.

// PHP 7
switch (8.0) {
  case '8.0':
    $result = "Oh no!";
  case 8.0:
    $result = "This is what I expected";
echo $result; //Output  Oh no!

// PHP 8
echo match (8.0) {
  '8.0' => "Oh no!",
  8.0 => "This is what I expected",
}; //Output  This is what I expected

That’s it!. Please share your thoughts or suggestions in the comments below.

Leave a Reply

Your email address will not be published. Required fields are marked *