0
0
PhpHow-ToBeginner · 4 min read

How to Use Match Expression in PHP: Syntax and Examples

In PHP, the match expression is used to compare a value against multiple conditions and return a result. It is similar to switch but more concise and returns a value directly without needing break statements.
📐

Syntax

The match expression compares a value against multiple cases and returns the matching result. It uses => to associate cases with their results. Unlike switch, it returns a value and does not require break statements.

  • value: The expression to match.
  • cases: Possible values to compare against.
  • result: The value returned if the case matches.
  • default: Optional; returned if no case matches.
php
match (value) {
    case1 => result1,
    case2 => result2,
    default => defaultResult,
};
💻

Example

This example shows how to use match to convert a number to a day name. It demonstrates returning a value directly and handling a default case.

php
<?php
$dayNumber = 3;
$dayName = match ($dayNumber) {
    1 => 'Monday',
    2 => 'Tuesday',
    3 => 'Wednesday',
    4 => 'Thursday',
    5 => 'Friday',
    6 => 'Saturday',
    7 => 'Sunday',
    default => 'Invalid day',
};
echo $dayName;
Output
Wednesday
⚠️

Common Pitfalls

Common mistakes when using match include:

  • Forgetting that match returns a value and must be assigned or used.
  • Using loose comparison; match uses strict comparison (===), so types must match exactly.
  • Not providing a default case, which causes an error if no match is found.
php
<?php
// Wrong: no assignment, no default, loose comparison
$number = '3';
match ($number) {
    1 => 'One',
    2 => 'Two',
    3 => 'Three', // This won't match because '3' !== 3
};

// Right: assign result, use default, strict types
$result = match ($number) {
    1 => 'One',
    2 => 'Two',
    '3' => 'Three',
    default => 'Unknown',
};
echo $result;
Output
Three
📊

Quick Reference

FeatureDescription
Returns a valueYes, unlike switch which is a statement
Comparison typeStrict (===)
Break statementsNot needed
Default caseOptional but recommended
Multiple conditions per caseSupported using comma-separated values

Key Takeaways

Use match to return values from multiple conditions with strict comparison.
Always assign the result of match to a variable or use it directly.
Include a default case to handle unmatched values and avoid errors.
No need for break statements as match does not fall through.
Multiple cases can be combined by separating values with commas.