PHP

What is the match expression in PHP?

PHP

The match expression was introduced in PHP 8. The match expression is pretty much the same as the switch statement, with just a few differences.

This compares identities with strict equality checks (===), rather than equalities with weaker checks (==)

Syntax

match expression usually has the following structure:

$temparature = 90;

$weather = match ($temparature) {
    30, 35,45 => "It's so cold Today",
    50 => "You need to wear sweater Today",
    75 => "Enjoy yourself, Not cold, not hot",
    90 => "The perfect beach weather!",
    default => "I don't know what to do with you"
};

echo $weather;
# out put: The perfect beach weather!

Explanation

In this example:

  • $temparature is the subject expression. Its value is compared with alternatives in the expression.
  • The values 30 to 90 are alternatives that are compared.
  • All the strings on the right side, “It’s so cold Today,” are the return expression
  • The example outputs “The perfect beach weather!”
  • Like switch statements, code in a match expression is only run if conditions before it failed.