iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

PHP Match (8.0+)

PHP 8.0 added match — an expression-based, strict-comparison replacement for the dusty switch statement.

Basic shape

PHP
$label = match ($status) {
    'paid'      => 'OK',
    'pending'   => 'Awaiting',
    'refunded'  => 'Refund issued',
    default     => 'Unknown',
};

How it differs from switch

matchswitch
Expression — returns a value.Statement.
Strict === compare.Loose == compare.
No fall-through. Each arm runs in isolation.Falls through unless you break.
Throws UnhandledMatchError if no arm matches and no default.Silently does nothing.
Multi-condition arms separated by commas.Stacked case labels.

Multiple conditions per arm

PHP
$type = match ($day) {
    'Sat', 'Sun'                       => 'weekend',
    'Mon', 'Tue', 'Wed', 'Thu', 'Fri'  => 'weekday',
};

No-condition match — same as if/elseif

PHP
$tier = match (true) {
    $score >= 90 => 'gold',
    $score >= 70 => 'silver',
    $score >= 50 => 'bronze',
    default      => 'fail',
};

Limits

  • Each arm is a single expression — no multi-line bodies. Wrap a function call if you need more logic.
  • The trailing comma after default => … is allowed and recommended.
Tip: For new code use match by default. UnhandledMatchError catches the case you forgot to handle — a great safety net.

Example

Example
<?php
// PHP 8.0+
$status = 'paid';
echo match ($status) {
    'paid'      => 'OK',
    'pending'   => 'Awaiting',
    'refunded'  => 'Refund issued',
    default     => 'Unknown',
};
Try it Yourself »

Exercise

Wildcard for the default arm.

match ($x) { 'a' => 1, => 0 }

Test yourself

Q1. match was added in PHP…
Q2. match comparison is…
Q3. If no arm matches and no default is given…

Discussion

Loading…