PHP Match Expression

PHP

PHP Match - Modern Conditional Expression

In this tutorial, you will learn about the PHP match expression, a modern alternative to traditional conditional statements like switch. Introduced in PHP 8.0, match offers improved readability, type safety, and concise syntax for pattern matching in your PHP code. We will cover its syntax, benefits, practical examples, best practices, and common mistakes to avoid, along with useful interview questions to test your understanding.

Prerequisites

  • Basic knowledge of PHP syntax and control structures
  • PHP 8.0 or higher installed on your system (match expression is not available in earlier versions)
  • A code editor or IDE to write and test PHP scripts

Setup

To get started, ensure your environment is running PHP 8.0 or above. You can check your PHP version with the following command in your terminal or command prompt:

php -v

If you need to install or upgrade, visit PHP official downloads page for installation instructions specific to your operating system.

Understanding PHP Match Expression

The match expression is similar in concept to switch, but it supports strict type comparison, returns values directly, and does not require break statements. It evaluates a single expression and matches its value against multiple arms (cases) to return the associated result.

Basic Syntax

match (expression) {
    value1 => result1,
    value2 => result2,
    default => default_result,
};
  • expression: The value or expression being matched.
  • value1, value2, ...: Possible values to match against the result of expression.
  • result1, result2, ...: The corresponding value that match will return if matched.
  • default: Optional arm that acts as fallback if no values match.

Key Features and Advantages Over Switch

  • Uses strict comparison (===) instead of loose comparison (==) in switch.
  • Returns a value, making it usable as an expression inside assignments.
  • No need for explicit break statements, so no accidental fall-through.
  • More concise and readable syntax with arrow operators =>.
  • Supports multiple matching values separated by commas.

Practical Examples

Example 1: Basic Match Expression

<?php
$role = 'editor';

$message = match ($role) {
    'admin' => 'You have full access.',
    'editor' => 'You can edit content.',
    'subscriber' => 'You can view content.',
    default => 'Role not recognized.',
};

echo $message; // Output: You can edit content.

Example 2: Matching Multiple Values

<?php
$grade = 'B';

$result = match ($grade) {
    'A', 'B' => 'Pass with good marks.',
    'C', 'D' => 'Pass.',
    'F' => 'Fail.',
    default => 'Invalid grade.',
};

echo $result; // Output: Pass with good marks.

Example 3: Using Match in Variable Assignment

<?php
$httpStatus = 404;

$statusMessage = match ($httpStatus) {
    200 => 'OK',
    301, 302 => 'Redirect',
    404 => 'Not Found',
    500 => 'Server Error',
    default => 'Unknown Status',
};

echo $statusMessage; // Output: Not Found

Example 4: Using Expressions as Results

<?php
$number = 10;

$message = match (true) {
    $number > 0 && $number <= 10 => 'Number is between 1 and 10',
    $number > 10 => 'Number is greater than 10',
    default => 'Number is zero or negative',
};

echo $message; // Output: Number is between 1 and 10

Best Practices

  • Always include a default arm to handle unexpected values and avoid unhandled expressions.
  • Prefer using match for discrete value checks rather than complex logic – use if-else when conditions are not value matches.
  • Leverage strict comparison behavior to prevent bugs caused by type coercion common in switch-case.
  • Use match expressions within assignments and return statements for clear and concise code.
  • For matching multiple values that should produce the same result, combine them in a comma-separated list for clarity.

Common Mistakes to Avoid

  • Forgetting the terminating semicolon ; after the match block.
  • Using loose comparison-style cases as with switch; match uses strict comparisons.
  • Not including a default arm and expecting it to handle unmatched values, which will throw an UnhandledMatchError.
  • Trying to use statements inside match arms rather than expressions (you cannot put multiple statements or imperative code directly inside match). Use functions or inline expressions instead.
  • Using match with complex conditional logic that is better suited to if-else statements.

Interview Questions

Junior Level

  • Q1: What PHP version introduced the match expression?
    A1: PHP 8.0 introduced the match expression.
  • Q2: How is the comparison done in a match expression?
    A2: The match expression uses strict comparison (===).
  • Q3: Do you need break statements in match?
    A3: No, match does not require break because it returns immediately.
  • Q4: Can match return a value?
    A4: Yes, match is an expression and returns a value.
  • Q5: Is a default arm mandatory in match?
    A5: No, but it is recommended to avoid unhandled match errors.

Mid Level

  • Q1: How can you match multiple values to the same result in a match expression?
    A1: By listing multiple values separated by commas before the arrow =>.
  • Q2: What kind of error occurs if no match is found and no default is provided?
    A2: An UnhandledMatchError is thrown.
  • Q3: Can conditions (like >, <) be used directly in the match arms? Give an example.
    A3: No, but you can use match(true) and place expressions in arms to mimic conditional behavior.
  • Q4: Compare match and switch with respect to type comparisons.
    A4: match uses strict (===) comparison, whereas switch uses loose (==) comparison.
  • Q5: What data types can be matched in a match expression?
    A5: Any scalar type (int, string, float, bool), objects implementing __toString(), but arms must be constant expressions.

Senior Level

  • Q1: How would you handle complex logic inside a match expression since arms only accept expressions?
    A1: Encapsulate complex logic in functions or methods and call them in the arm's expression.
  • Q2: Explain the implications of using match(true) idiom in PHP.
    A2: Using match(true) allows for condition matching by evaluating each arm’s expression, but can reduce clarity and should be used carefully.
  • Q3: Can match be used with enum cases introduced in PHP 8.1? Give an example.
    A3: Yes, you can match enum cases directly, for example: match ($status) { UserStatus::Active => ..., ... };
  • Q4: Describe how match's strict comparison behavior can prevent bugs compared to switch.
    A4: Since match uses strict comparison, it avoids unexpected matches due to type coercion common in switch, leading to more predictable behavior.
  • Q5: Can a match arm throw an exception? How to structure it?
    A5: Yes, an arm can throw an exception if the arm expression is a function or method that does so; you cannot directly place a throw statement inline.

FAQ

What versions of PHP support the match expression?

Match expression is supported beginning from PHP 8.0 onwards.

Is the match expression faster than switch?

Performance differences are minimal; however, match can be cleaner and less error-prone due to strict typing and lack of fall-through.

Can match handle multiple data types simultaneously?

Yes, but since it uses strict comparison, make sure types are exact matches; mixing types in arms is allowed as long as they are constants.

Can I use match without a default case?

You can omit default, but if no case matches, PHP throws an UnhandledMatchError, which should be handled.

Are there any limitations on expressions used in match arms?

Arms must be constant expressions or calls to pure functions; you cannot include statements or assignments directly inside arms.

Conclusion

The match expression is a powerful, modern construct in PHP that simplifies complex conditionals and improves code clarity by enforcing strict comparisons and returning values directly. It is a practical tool to replace traditional switch cases, reducing bugs related to fall-through and type coercion. With this tutorial, you are equipped with the knowledge to use match effectively in your PHP projects and can confidently answer relevant interview questions.