PHP Match Expression - Match vs Switch

mainick

Maico Orazio

Posted on October 2, 2023

PHP Match Expression - Match vs Switch

The Match expression is essentially the same as the Switch statement and was introduced in PHP 8.

The keyword is match, so let's recreate the switch statement below:

$paymentStatus = 1;

switch ($paymentStatus) {
  case 1:
    echo 'Paid';
    break;
  case 2:
  case 3:
    echo 'Payment Declined';
    break;
  case 0:
    echo 'Pending Payment';
    break;
  default:
    echo 'Unknown Payment Status';
    break;
}
Enter fullscreen mode Exit fullscreen mode

Inside the curly braces, we form pairs of values where the key is the individual conditional expression, and the value is the return expression.

$paymentStatusDisplay = match ($paymentStatus) {
  1 => 'Paid',
  2,3 => 'Payment Declined',
  0 => 'Pending Payment',
  default => 'Unknown Payment Status',
};
echo $paymentStatusDisplay;
Enter fullscreen mode Exit fullscreen mode

Let's talk about the differences

The first difference is that the match expression is actually an expression and evaluates to a value, so it can be assigned to a variable. It can be practically any type of expression; for example, we could use a function that returns a value.

The second difference is that switch requires the use of break to avoid some unexpected outcomes, such as the evaluation of other case statements, while the match statement returns a value once a match is found.

The third difference is that in the switch statement, the default value is not required, whereas a fatal error is generated in match if a corresponding match is not found in any of the listed cases and the default value is not specified.

The fourth difference is that the match expression performs a strict comparison while the switch statement performs loose comparison. Both sides are expressions, and we could have complex expressions, function calls, logical operators used within a conditional expression.

$paymentStatus = false;
// switch print 'Pending Payment'
// match print 'Unknown Payment Status'
Enter fullscreen mode Exit fullscreen mode

One thing to note is that the match expression does not deprecate the switch statement as it still has its use cases. For example, match returns a value once a match is found, whereas with switch, you can execute multiple statements.

Good work 👨‍💻

💖 💪 🙅 🚩
mainick
Maico Orazio

Posted on October 2, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related