PHP8: Match Expressions

Switch statements in PHP are useful, yet clunky. Think of the new match expression in PHP 8 as an improved switch. It’s far more flexible than its counterpart.

Usage: Replace the switch statement with a match in PHP8, match expressions can also return a value. Let’s take a look at few example how to use match expressions feature.

Example: how to replace switch with match?


switch ($action) {
    case 'import-posts':
        $status = $this->importPosts();
    case 'update-posts':
    case 'sync-posts':
        $status = $this->updatePosts();
        throw new \Exception('Unsupported');

Let’s see how this can be replace by match expressions


As we can see in following example code looks very simple, just few lines vs example above. Match expression can be assigned to the variable also as you can see in the following block.

$status = match($action) {
    'import-posts' => $this->importPosts(),
    'update-posts', 'sync-posts' =>  $this->updatePosts(),
    default => throw new \Exception('Unsupported'),

Match expressions can return a value, what does it mean? Let’s take a look at example below.

$gender = match(2) {
    1 => 'Male',
    2 => 'Female',

echo $gender; // "Female"

The return value of the expression used in each “arm” (similar to each case in switch blocks) is can be assigned to a variable.

Match expression MUST match a condition, In a match expression, there must be condition that matches the expression, or a default case to handle it. If there are no matches, match expression throws an \UnhandledMatchError exception.

Things to remember:

  • Multiple matching conditions allowed
  • Each matching case must only contain one expression
  • Implicit break: Sharing well-described below

default case

default arm will catch all expressions if none of the other conditions matched.

match vs switch

switch match
Requires PHP ^8.0 No Yes
Returns value No Yes
default condition support Yes Yes
Multiple conditions in single arm Yes Yes
Multiple expressions in code block Yes No
Implicit break No Yes
Falls-through without break Yes No
Throws an exception on no matches No Yes
Match against arbitrary expressions Yes Yes
Strict type-safe comparison No Yes
Author: Danyal
I'm working as programmer since 2002. Born, grew up, studied and worked in Pakistan now Im located in Denmark since 2006.