match evaluates a subject with strict comparison and returns the chosen arm's expression.
What It Does
match evaluates a subject with strict comparison and returns the chosen arm's expression. The following examples distinguish a normal use case, a boundary case and a practical application.
Requirements and Compatibility
PHP 8.x and a local test environment. Apply input validation, correct error handling and the requirements of any optional libraries.
The code focuses on the core concept. Production implementation may also need routes, validation, persistence, authorization or deployment tooling.
Example 1: Basic Behavior
Start with the smallest meaningful working case.
<?php
$status = 201;
echo match ($status) { 200 => 'OK', 201 => 'Created', 404 => 'Not found', default => 'Other' };
Example 2: Another Case
Examine the edge case and the observable result.
<?php
try { echo match ('paused') { 'new' => 0, 'done' => 1 }; } catch (UnhandledMatchError $e) { echo 'No matching arm'; }
Practical Example: Putting It to Use
Apply the technique to a small practical task.
<?php
$total = 15;
$band = match (true) { $total >= 100 => 'large', $total >= 10 => 'medium', default => 'small' };
echo $band;
Important Behavior and Edge Cases
A missing default and no matching arm raise UnhandledMatchError.
Comparison with Related Functions or Approaches
| Option | What it means in practice |
|---|---|
| Match Expressions | match evaluates a subject with strict comparison and returns the chosen arm's expression. |
| Related approach | switch supports statement blocks and fallthrough but uses different comparison semantics. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Ignoring the important boundary for Match Expressions | A missing default and no matching arm raise UnhandledMatchError. |
| Assuming a related mechanism has the same behavior | switch supports statement blocks and fallthrough but uses different comparison semantics. |
Key Takeaways
- match evaluates a subject with strict comparison and returns the chosen arm's expression.
- A missing default and no matching arm raise UnhandledMatchError.
- switch supports statement blocks and fallthrough but uses different comparison semantics.
Before adapting these examples, verify the return values, test the failure paths and confirm that your application meets its security and environment requirements.