← CodeClarityLab Home
Browse by Category
+ added · updated 7d
← Back to glossary

match Expression (PHP 8.0)

php PHP 8.0+ Beginner

TL;DR

PHP 8.0's match is a stricter switch — uses strict (===) comparison, each arm is an expression (not statements), returns a value, and throws UnhandledMatchError if no arm matches.

Explanation

match($x) { pattern => value, ... } differences from switch: strict comparison (===, no coercion), each arm is a single expression (no statements, no break needed), match returns a value (expression, not statement), no fall-through (comma-separated patterns for multiple matches), throws UnhandledMatchError with no match and no default. Multiple patterns per arm: 1, 2 => 'low'. Combining with null coalescing: $result = match(true) { $a > 0 => 'positive', default => 'zero or negative' }. Works with enums (PHP 8.1): match($status) { Status::Active => ... }.

Common Misconception

match is just syntactic sugar for switch — match uses strict comparison (no type coercion), returns values, throws on no match, and has no fall-through.

Why It Matters

match replaces switch for value-returning contexts and eliminates switch's type coercion bugs — a safer, more expressive alternative.

Common Mistakes

  • Forgetting default arm — throws UnhandledMatchError.
  • Trying multi-statement arms — each arm is one expression.
  • Not knowing match uses === — helps avoid type coercion bugs common in switch.

Code Examples

✗ Vulnerable
switch ($status) {
    case 'active': $label = 'Active'; break;
    case 'inactive': $label = 'Inactive'; break;
    default: $label = 'Unknown';
}
✓ Fixed
$label = match($status) {
    'active'   => 'Active',
    'inactive' => 'Inactive',
    default    => throw new InvalidArgumentException("Unknown: $status")
};

// Multiple patterns:
$type = match($code) {
    200, 201, 202 => 'success',
    400, 422      => 'client error',
    500, 503      => 'server error',
};

Added 23 Mar 2026
Views 22
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
1 ping F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 0 pings F 0 pings S 1 ping S 0 pings M 0 pings T 1 ping W 0 pings T 1 ping F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 1 ping T 1 ping F 1 ping S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 0 pings F 1 ping S
No pings yesterday
Amazonbot 6 Unknown AI 3 Perplexity 3 Google 2 SEMrush 2 ChatGPT 1 Ahrefs 1
crawler 16 crawler_json 1 pre-tracking 1
DEV INTEL Tools & Severity
🔵 Info ⚙ Fix effort: Low
⚡ Quick Fix
Replace switch blocks that return values with match expressions. Always add default arm. Use comma-separated patterns for multiple matches.
📦 Applies To
PHP 8.0+ web cli queue-worker
🔗 Prerequisites
🔍 Detection Hints
switch\s*\(
Auto-detectable: ✓ Yes rector phpcs
🤖 AI Agent
Confidence: Medium False Positives: Medium ✓ Auto-fixable Fix: Low Context: Function

✓ schema.org compliant