Pattern matching

suggest change

PHP 8.0 introduced the match expression, providing safe, concise, and expressive pattern matching. Unlike the legacy switch statement, match evaluates to a return value, enforces strict comparison (===), does not require break statements, and enforces exhaustiveness.

match vs. switch

Feature switch statement match expression
Return Value None (statement) Returns a value (expression)
Comparison Loose equality (==) Strict identity (===)
Fallthrough Yes (requires explicit break) No fallthrough (multiple keys separated by commas)
Exhaustiveness Unmatched values silently pass Throws UnhandledMatchError if unhandled and no default

Basic Syntax and Value Assignment

Because match is an expression, you can assign its result directly to a variable or return it:

$httpStatusCode = 200;

$message = match ($httpStatusCode) {
    200, 201, 204 => 'Success',
    400, 422      => 'Client Error: Validation failed',
    401, 403      => 'Client Error: Unauthorized',
    404           => 'Client Error: Not Found',
    500           => 'Server Error: Internal error',
    default       => 'Unknown status code',
};

echo $message; // Success

Strict Type Safety

A common source of bugs in switch statements is PHP's loose type coercion (e.g., 0 == 'hello' in earlier PHP versions). match uses strict identity checks (===):

$input = '0';

// In switch, '0' might match integer 0 loosely
// In match, types must match strictly:
$label = match ($input) {
    0       => 'Integer zero',
    '0'     => 'String zero', // Matches here
    default => 'Other',
};

echo $label; // String zero

Arbitrary Expressions and Ranges (match (true))

You can match against arbitrary conditional expressions, ranges, and predicates by passing true to the match expression:

$score = 85;

$grade = match (true) {
    $score >= 90 => 'A',
    $score >= 80 => 'B',
    $score >= 70 => 'C',
    $score >= 60 => 'D',
    default      => 'F',
};

echo "Grade: $grade"; // Grade: B

Matching Against Object Types (instanceof)

Using match (true) provides an elegant way to handle polymorphic events or domain command objects without long if-elseif-else chains:

abstract class PaymentEvent {}
class CardCharged extends PaymentEvent { public int $amount = 100; }
class PaymentRefunded extends PaymentEvent { public int $amount = 50; }
class PaymentFailed extends PaymentEvent { public string $reason = "Declined"; }

function handleEvent(PaymentEvent $event): string {
    return match (true) {
        $event instanceof CardCharged => "Charged: \${$event->amount}",
        $event instanceof PaymentRefunded => "Refunded: \${$event->amount}",
        $event instanceof PaymentFailed => "Failed: {$event->reason}",
    };
}

echo handleEvent(new CardCharged()); // Charged: $100

Matching with PHP 8.1+ Enums

When combined with Enums, match ensures that every possible enum case is handled:

enum OrderStatus: string
{
    case Pending = 'pending';
    case Processing = 'processing';
    case Shipped = 'shipped';
    case Delivered = 'delivered';
    case Cancelled = 'cancelled';
}

function getStatusBadge(OrderStatus $status): string
{
    return match ($status) {
        OrderStatus::Pending    => 'badge-warning',
        OrderStatus::Processing => 'badge-info',
        OrderStatus::Shipped    => 'badge-primary',
        OrderStatus::Delivered  => 'badge-success',
        OrderStatus::Cancelled  => 'badge-danger',
    };
}

If a new case is later added to OrderStatus and not handled here, PHP throws an UnhandledMatchError at runtime as soon as that case reaches this match, alerting you to update all related handlers.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents