In the latest version of PHP (8.0), a new feature known as match expressions has been introduced. This feature is a simpler and more helpful way to check conditions than the traditional switch statement. This tutorial guides you on how to code using this new feature effectively.



What is the Match Expression?

The match expression is a new addition in PHP 8.0, providing a new way to handle multiple conditional checks. It is similar to the switch statement but with the following key differences:

  • Concise Syntax: Match provides a more concise and readable syntax compared to the traditional switch statement. 
  • Return Value: Unlike the switch, the match expression returns a value, allowing for direct assignment to a variable or inclusion in other expressions.
  • Strict Comparisons: While the switch statement uses loose comparison (==), match employs strict comparison (===). This ensures the value and type match precisely, eliminating confusion between data types like integers and strings. 
  • Versatility in Matching: With the match expression, it's possible to match multiple values to a single outcome simply by separating them with commas.
  • No Breaks Required: There's no need for a break statement after each case in a match expression, unlike the switch statement.
  • Optional Default Arm: The default arm is not mandatory in a match. However, if a pattern is not aligned and the default is absent, PHP will trigger an UnhandledMatchError.

Basic Syntax

Here's the fundamental structure for the match expression:

$result = match ($expression) {
    single_value_or_expression => return_value_when_matched,
    another_value_or_expression => another_return_value_when_matched,
    // ... additional cases
    default => return_value_when_no_cases_match,
};

It is clear from the above structure that using a match expression is more efficient, as it eliminates the need for multiple case and break statements commonly used in switch statements.

Simple Usage Example

Here are a few examples demonstrating the usage of the match expression:

Value Mapping

Let us take an example of converting a number into its description:

$number = 2;
$text = match($number) {
    1 => 'One',
    2 => 'Two',
    3 => 'Three',
    default => 'Not in range',
};
echo $text; // Displays: Two

Match Multiple Values

Another example of the match expression for grouping several values to yield a single return:

$day = 'Tue';

$result = match ($day) {
    'Mon', 'Tue', 'Wed', 'Thu', 'Fri' => 'Weekday',
    'Sat', 'Sun' => 'Weekend',
    default => 'Invalid day'
};

echo $result; // Displays: "Weekday"

Expressions in Match Arms

The match arms can evaluate more complex expressions:

$value = 20;

$result = match (true) {
    $value > 10 && $value < 50 => 'Between 10 and 50',
    $value <= 10 => '10 or below',
    default => 'Other'
};

echo $result; // Displays: "Between 10 and 50"

Example of Replacing switch with match

Here's an example of how a match expression can replace a switch statement:

Using switch

switch ($number) {
    case 1:
        $result = 'one';
        break;
    case 2:
        $result = 'two';
        break;
    default:
        $result = 'unknown number.';
        break;
}

Using match

$result = match ($number) {
    1 => 'one',
    2 => 'two',
    default => 'unknown number.'
};

Real-world Use Case

Consider a website where users are assigned roles such as 'administrator', 'editor', and 'user'. In this case, the match expression can be utilized to get their respective permissions efficiently:

$role = 'editor';

$permissions = match($role) {
    'admin' => ['create', 'edit', 'delete', 'view'],
    'editor' => ['edit', 'view'],
    'user' => ['view'],
    default => []
};

print_r($permissions);

Program Output:

Array
(
    [0] => edit
    [1] => view
)

Conclusion

In general, utilizing match expressions can significantly enhance PHP development by improving code clarity and minimizing potential mistakes. Its practical application in simplifying value mapping and refining role-based permissions demonstrates the effectiveness of modern coding practices in driving efficiency and clarity.



Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram