Matthew Hodge
Full Stack Developer

PHP 8 introduced a new feature called match expression, which is similar to the switch statement but with some key differences and improvements. This post will explain the differences between switch and match and provide examples to illustrate their usage.

For more details, you can refer to the official PHP documentation.

Differences between switch and match

  1. Return Value: The match expression returns a value, whereas the switch statement does not.
  2. Strict Comparison: match uses strict comparison (===), while switch uses loose comparison (==).
  3. No Fall-through: match does not allow fall-through, which means each case must be unique and there is no need for break statements.
  4. Expression-based: match is an expression and can be used in assignments, while switch is a statement.

Example 1: Basic Usage

Using switch

$input = 2;
$result = '';

switch ($input) {
    case 1:
        $result = 'One';
        break;
    case 2:
        $result = 'Two';
        break;
    case 3:
        $result = 'Three';
        break;
    default:
        $result = 'Unknown';
        break;
}

echo $result; // Outputs: Two

Using match

$input = 2;

$result = match ($input) {
    1 => 'One',
    2 => 'Two',
    3 => 'Three',
    default => 'Unknown',
};

echo $result; // Outputs: Two

Example 2: Type Safety

Using switch

<?php
$input = '2';
$result = '';

switch ($input) {
    case 1:
        $result = 'One';
        break;
    case 2:
        $result = 'Two';
        break;
    case 3:
        $result = 'Three';
        break;
    default:
        $result = 'Unknown';
        break;
}

echo $result; // Outputs: Two (loose comparison)

Using match

<?php
$input = '2';

$result = match ($input) {
    1 => 'One',
    2 => 'Two',
    3 => 'Three',
    default => 'Unknown',
};

echo $result; // Outputs: Unknown (strict comparison)

As you can see, the match expression provides a more concise and safer way to handle conditional logic compared to the switch statement. It ensures strict type comparisons and eliminates the risk of fall-through errors.

By understanding and utilizing the match expression, you can write cleaner and more predictable code in PHP 8 and beyond.