PHP match Expression

The match Expression in PHP is a shorthand syntax for switch statements. It was introduced in PHP 8.0 and provides a simpler and more concise way to compare a value against multiple conditions.

Here is the syntax for the match function:

Here’s an example of how to use the match Expression to check if a number is positive, negative, or zero:

$num = 5;

$result = match(true) {
  $num > 0 => "positive",
  $num < 0 => "negative",
  default => "zero",

echo $result; // Output: "positive"

In the example above, we used the true keyword as the input value for the match Expression. This is because we’re not actually matching against a value, but rather comparing the input value against each of the conditions.

We then used three cases to check whether the value of $num is greater than 0, less than 0, or equal to 0. If $num matches any of these conditions, the corresponding string (“positive”, “negative”, or “zero”) is returned.

If none of the cases match, the default case is executed, which simply returns the string “zero”.

Note that the match Expression is similar to the switch statement, but with some key differences. One difference is that match expressions can return values, while switch statements cannot. Additionally, match expressions use strict comparison (===) by default, while switch statements use loose comparison (==) by default.

Share this:

Leave a Reply

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