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
matchreturns a value and must be assigned or used. - Using loose comparison;
matchuses strict comparison (===), so types must match exactly. - Not providing a
defaultcase, 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
| Feature | Description |
|---|---|
| Returns a value | Yes, unlike switch which is a statement |
| Comparison type | Strict (===) |
| Break statements | Not needed |
| Default case | Optional but recommended |
| Multiple conditions per case | Supported 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.