PHP Match

JA JASWANT Updated 16 Oct 2026
8 min read ·Lesson 3 of 248
In this post

What Is the match Expression? In simple terms: match (PHP 8.0+) checks a value against a list of possibilities and returns the result for the first one that matches. It is a safer, shorter alternative

What Is the match Expression?

In simple terms: match (PHP 8.0+) checks a value against a list of possibilities and returns the result for the first one that matches. It is a safer, shorter alternative to switch for choosing a value.

Technically: match is an expression. It evaluates a subject expression, compares it with each arm's conditions using strict comparison (===), and returns the result of the first matching arm. There is no fall-through, and if no arm matches, PHP throws an UnhandledMatchError.

Why match Was Added

switch has three well-known weaknesses:

  1. Loose comparison (==) causes unexpected matches, such as '0' matching false.
  2. Fall-through: a forgotten break silently runs the next case.
  3. It is a statement, so producing a value requires assigning a variable in every case.

match fixes all three.


Syntax

$result = match (subjectExpression) {
    condition1 => resultExpression1,
    condition2, condition3 => resultExpression2,
    default => defaultResultExpression,
};
PartMeaning
match (subjectExpression)The value to test, evaluated once
condition => resultAn arm: if the subject is identical (===) to the condition, the result is returned
condition2, condition3 =>Several conditions sharing one result, separated by commas
default =>Result when no other arm matches (optional)
;match is an expression, so the statement that uses it ends with a semicolon

Example

<?php
$status = 'shipped';

$label = match ($status) {
    'pending' => 'Awaiting payment',
    'paid', 'processing' => 'Preparing your order',
    'shipped' => 'On the way',
    'delivered' => 'Delivered',
    default => 'Unknown status',
};

echo $label;

Output

On the way

How It Works

  1. The subject $status is evaluated once: 'shipped'.
  2. PHP compares it with each arm's conditions from top to bottom using ===.
  3. The arm 'shipped' => 'On the way' matches, so its result is returned and assigned to $label.
  4. No break is needed — match never falls through to other arms.
  5. 'paid', 'processing' shows how several values share one result.

Strict Comparison

match compares with ===, so both value and type must match.

Example: match vs switch

<?php
$value = '1';

$withMatch = match ($value) {
    1 => 'integer one',
    '1' => 'string one',
};

switch ($value) {
    case 1:
        $withSwitch = 'integer one';
        break;
    case '1':
        $withSwitch = 'string one';
        break;
}

echo "match:  $withMatch\n";
echo "switch: $withSwitch\n";

Output

match:  string one
switch: integer one

switch uses ==, so the string '1' matches the integer case 1 first. match skips it because the types differ and finds the correct arm.

Consequence for Input Data

Values from forms and URLs are strings. If your arms use integers, convert the input first:

<?php
$pageInput = '2';   // from $_GET

$title = match ((int) $pageInput) {
    1 => 'Introduction',
    2 => 'Installation',
    3 => 'Syntax',
    default => 'Lesson not found',
};

echo $title;

Output

Installation

Without the (int) cast, '2' would not be identical to 2, and the result would be 'Lesson not found'.


No Match: UnhandledMatchError

If no arm matches and there is no default, match throws an UnhandledMatchError:

<?php
$status = 'archived';

try {
    $label = match ($status) {
        'draft' => 'Draft',
        'published' => 'Published',
    };
} catch (\UnhandledMatchError $e) {
    echo get_class($e) . " caught: no arm handles '$status'\n";
}

Output

UnhandledMatchError caught: no arm handles 'archived'

The error message itself includes the unhandled value (its exact wording differs slightly between PHP versions).

Why Throwing Is Good

With switch, an unexpected value silently does nothing, and the bug appears later — for example, as an undefined variable. match fails immediately and loudly at the place where the unexpected value appeared. Add a default arm only when there is a sensible fallback; otherwise, let match throw so that missing cases are discovered during development.

Throwing a Custom Exception

Since PHP 8.0, throw is also an expression, so it can be used as an arm's result:

<?php
function boxPrice(string $size): int
{
    return match ($size) {
        'S' => 49,
        'M' => 79,
        'L' => 119,
        default => throw new InvalidArgumentException("Unknown box size: $size"),
    };
}

echo boxPrice('M') . "\n";

try {
    echo boxPrice('XL') . "\n";
} catch (InvalidArgumentException $e) {
    echo "Error: " . $e->getMessage() . "\n";
}

Output

79
Error: Unknown box size: XL

A descriptive exception is easier to understand in logs than a generic UnhandledMatchError.


Only the Matching Arm Is Evaluated

Arm results are evaluated lazily: only the result of the matching arm runs.

<?php
function loadAdminDashboard(): string
{
    echo "(loading admin data...)\n";
    return 'Admin dashboard';
}

function loadUserDashboard(): string
{
    echo "(loading user data...)\n";
    return 'User dashboard';
}

$role = 'user';

$page = match ($role) {
    'admin' => loadAdminDashboard(),
    'user' => loadUserDashboard(),
    default => 'Guest page',
};

echo $page . "\n";

Output

(loading user data...)
User dashboard

loadAdminDashboard() is never called. This makes it safe to put function calls in arms.


match (true): Matching Conditions

When the subject is true, each arm's condition can be any boolean expression. The first condition that is true wins. This is the standard way to handle ranges:

<?php
function grade(int $score): string
{
    return match (true) {
        $score >= 90 => 'A',
        $score >= 75 => 'B',
        $score >= 60 => 'C',
        default => 'F',
    };
}

foreach ([95, 82, 67, 45] as $score) {
    echo "$score: " . grade($score) . "\n";
}

Output

95: A
82: B
67: C
45: F

How It Works

  • Each condition (for example $score >= 75) evaluates to true or false.
  • match compares that result with the subject true using ===.
  • Arms are checked in order, so they must go from the highest threshold to the lowest — the same rule as an if...elseif chain.

Note: Conditions in match (true) must produce real booleans. A condition such as $name (a non-empty string) is truthy but not identical to true, so it would not match. Use explicit comparisons like $name !== ''.


Practical Example: HTTP Status Messages

<?php
function statusText(int $code): string
{
    return match ($code) {
        200 => 'OK',
        201 => 'Created',
        301, 302 => 'Redirect',
        400 => 'Bad Request',
        401, 403 => 'Access Denied',
        404 => 'Not Found',
        500 => 'Server Error',
        default => 'Unknown status',
    };
}

foreach ([200, 302, 403, 404, 418] as $code) {
    echo "$code: " . statusText($code) . "\n";
}

Output

200: OK
302: Redirect
403: Access Denied
404: Not Found
418: Unknown status

Grouping codes with commas (301, 302) keeps related values together without repeating the result.


Practical Example: Subscription Pricing

<?php
function subscriptionPrice(string $plan, string $cycle): int
{
    $monthly = match ($plan) {
        'basic' => 299,
        'pro' => 799,
        'business' => 1999,
        default => throw new InvalidArgumentException("Unknown plan: $plan"),
    };

    return match ($cycle) {
        'monthly' => $monthly,
        'yearly' => (int) round($monthly * 12 * 0.8),   // 20% yearly discount
        default => throw new InvalidArgumentException("Unknown billing cycle: $cycle"),
    };
}

$requests = [['basic', 'monthly'], ['pro', 'yearly'], ['business', 'yearly'], ['enterprise', 'monthly']];

foreach ($requests as [$plan, $cycle]) {
    try {
        echo "$plan ($cycle): ₹" . number_format(subscriptionPrice($plan, $cycle)) . "\n";
    } catch (InvalidArgumentException $e) {
        echo "Error: " . $e->getMessage() . "\n";
    }
}

Output

basic (monthly): ₹299
pro (yearly): ₹7,670
business (yearly): ₹19,190
Error: Unknown plan: enterprise

Step-by-Step Explanation

  1. The first match maps the plan name to a monthly price, or throws for an unknown plan.
  2. The second match calculates the final price for the billing cycle. The yearly price is 12 months with a 20% discount: 799 × 12 × 0.8 = 7670.4, rounded to 7670.
  3. (int) round(...) converts the rounded float to an integer.
  4. Each match has a single responsibility, which keeps the function easy to extend: adding a plan means adding one arm.

match vs switch

Featureswitchmatch
TypeStatementExpression (returns a value)
ComparisonLoose (==)Strict (===)
Fall-throughYes, without breakNever
Multiple values per branchStacked case labelsComma-separated conditions
Branch bodyAny number of statementsOne expression
No matching branchDoes nothing (unless default)Throws UnhandledMatchError
Available sinceEarly PHPPHP 8.0

When to Use Which

  • Use match to choose or calculate a value from a single input — the most common case.
  • Use switch or if...elseif when a branch must execute several statements (or call a function that does the work and return its result from a match arm).
  • Use match (true) for range checks that return a value.

Common Mistakes

Forgetting the Semicolon

Effect: Parse error. match is part of an assignment or return statement, which needs a closing ; after the }.

Fix: $x = match (...) { ... };

Comparing Strings With Integer Arms

Effect: Input such as '2' does not match 2, leading to the default arm or an UnhandledMatchError.

Fix: Cast or validate input before matching.

Writing Statements Inside Arms

Effect: Parse error — arms accept a single expression, not blocks of statements.

Fix: Move multi-step logic into a function and call it from the arm, or use switch / if.

Using Non-Boolean Conditions in match (true)

Effect: Truthy values (non-empty strings, non-zero numbers) do not match true.

Fix: Use explicit comparisons that return booleans.

Adding default Too Eagerly

Effect: Unexpected values are hidden behind a generic fallback.

Fix: Use default only when the fallback is genuinely correct; otherwise, let the error surface or throw a descriptive exception.


Best Practices

  • Prefer match over switch for value selection in PHP 8 code.
  • Normalize input types before matching, because comparison is strict.
  • Group values that share a result with commas.
  • Use match (true) for ordered range checks, from the most specific condition to the least.
  • Throw descriptive exceptions in default arms for invalid input.

Official reference: https://www.php.net/manual/en/control-structures.match.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Home PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope PHP Casting Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence Continue Statement Modify Strings PHP If...Else...Elseif PHP If Modify Strings PHP If Operators PHP Functions Concatenate Strings PHP If...Else User-defined Functions Slicing Strings Function Arguments PHP Shorthand if Escape Characters Default Argument Values PHP Nested if Pass by Reference String Interpolation Named Arguments PHP File Upload Variadic Functions Return Values Search in Strings Multibyte Strings Type Declarations in Functions PHP Numbers PHP Math PHP Floats PHP Random Numbers PHP Constants PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Cookies PHP Destructor PHP Access Modifiers Readonly Properties PHP Sessions PHP Inheritance Method Overriding PHP Filters The final Keyword CSRF Protection PHP Filters Advanced Session Security Secure Cookies PHP Magic Constants File Upload Security PHP Callback Functions PHP Operators Filesystem Security PHP JSON Arithmetic Operators Error Reporting in Production Hiding PHP Assignment Operators PHP Configuration (php.ini) Comparison Operators PHP Command Line (CLI) PHP Exceptions Increment / Decrement Operators Migrating to PHP 8 PHP Form Validation PHP Form Required PHP Form URL/E-mail Error Handling Form Input Sanitizing Escaping Output (htmlspecialchars) Custom Error Handler Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention Garbage Collection Project: Simple Blog PHP What is OOP PHP Classes/Objects The $this Keyword Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where Debugging PHP Project: Image Upload Gallery $_SESSION $_ENV PHP RegEx RegEx Patterns Heredoc and Nowdoc RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures Composer PHP Form Handling PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro PHP Class Constants Encryption with Sodium Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS What Is `$_SERVER` ? $_REQUEST $_POST $_GET $_FILES $_COOKIE PHP Type Juggling MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data MySQL Joins with PHP Pagination with PHP PDO Introduction PDO Connect PDO Prepared Statements PDO Fetch Modes PSR-4 Autoloading Installing Extensions (PECL / PIE) OPcache & Performance PHP-FPM Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Shopping Cart with Sessions Project: REST API with PHP DateTime Class Timezones PHP Include Include vs Require PHP File Handling PHP File Open/Read PHP File Create/Write File Delete / Rename / Copy PHP Directories PHP CSV Files
Ask about this post
AI Ask about this post

Ask questions about PHP Match and get answers drawn from it.

Signed-in readers only.