The cart is empty

PHP 8 introduces numerous enhancements, including the new language construct - match expression. This article will delve into the syntax, benefits, and practical usage of match expression in PHP 8.

Syntax of match expression

Match expression in PHP 8 provides a simpler and more readable way to compare values compared to the traditional switch statement. The basic syntax is as follows:

$result = match($variable) {
    value1 => result1,
    value2 => result2,
    default => defaultResult,
};

The main differences from the switch statement include:

  • Return value: Match expression returns a value that can be assigned to a variable.
  • Strict type comparison: Match expression uses strict type comparison (===).
  • Implicit break: There is no need for break statements; each case is defined by an arrow (=>).

Benefits of match expression

Cleaner and more readable code: Match expression ensures more readable code without the need for break statements and allows direct value assignment.

Strict type comparison: Unlike the switch statement, which uses loose comparison (==), match expression uses strict comparison (===), providing more accurate and safer comparisons.

Expression syntax: Match expression can be used as part of expressions, allowing value assignments or function calls directly within the match cases.

Practical Usage

To better understand, let's look at some practical examples of how to use match expression.

Simple Example

$status = 200;

$message = match($status) {
    200 => 'OK',
    404 => 'Not Found',
    500 => 'Internal Server Error',
    default => 'Unknown Status Code',
};

echo $message; // Output: OK

Usage with Functions

function getStatusMessage(int $status): string {
    return match($status) {
        200 => 'OK',
        404 => 'Not Found',
        500 => 'Internal Server Error',
        default => 'Unknown Status Code',
    };
}

echo getStatusMessage(404); // Output: Not Found

More Complex Logic

$userRole = 'admin';

$permissions = match($userRole) {
    'admin' => ['create', 'read', 'update', 'delete'],
    'editor' => ['create', 'read', 'update'],
    'viewer' => ['read'],
    default => [],
};

print_r($permissions); // Output: Array ( [0] => create [1] => read [2] => update [3] => delete )

Comparing with Multiple Conditions

$input = 42;

$output = match(true) {
    $input < 10 => 'Small',
    $input >= 10 && $input <= 50 => 'Medium',
    $input > 50 => 'Large',
    default => 'Unknown Size',
};

echo $output; // Output: Medium

Match expression in PHP 8 significantly simplifies and clarifies code for cases where different actions need to be performed based on variable values. With strict comparison and the ability to return values directly, match expression becomes a powerful tool for developers aiming to write clean and maintainable code.