CGPA Calculator Hash Generator Bcrypt Hasher Tree Visualizer Barcode Generator Engineering Blog Editorial Standards All Tools Games HTML5 JavaScript PHP MySQL

PHP Match Expression

Introduced in PHP 8.0, the match expression is a more powerful and concise version of the switch statement. It allows you to select a value based on a condition and returns that value directly to a variable or into an output.


Basic Syntax

Unlike switch, match uses a comma-separated syntax and doesn't require break or case keywords.

<?php
    $food = "cake";

    $return_value = match ($food) {
        "apple" => "This food is a fruit",
        "bar" => "This food is a candy bar",
        "cake" => "This food is a dessert",
        default => "Unknown food",
    };

    echo $return_value; // Outputs: This food is a dessert
?>

Match vs. Switch

The match expression fixes several "weird" behaviors of switch:

Feature Switch Match
Category Statement Expression (returns a value)
Comparison Loose (==) Strict (===)
Break Required to stop fall-through Implicit (no fall-through)
Multiple values Requires multiple case blocks Comma-separated on one line

Multiple Values in One Arm

You can match multiple search values to a single result arm easily:

<?php
    $age = 15;

    $result = match (true) {
        $age >= 18 => "Adult",
        $age < 18 => "Minor",
    };

    echo $result;
?>
Strict Comparison: match uses ===. This means "10" will NOT match an integer 10. This makes your code significantly safer and less prone to type-related bugs.
Constraint: The match expression must be exhaustive. If no default is provided and no match is found, PHP will throw an UnhandledMatchError.

Key Points to Remember

  • The match expression is available in PHP 8.0 and higher.
  • It returns a value, making it very concise for assignments.
  • It uses strict comparison (===) by default.
  • There is no fall-through logic; the first match stops execution.
  • Always provide a default arm unless you are 100% sure a match will occur.