0
0
PHPprogramming~10 mins

Match expression (PHP 8) - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Match expression (PHP 8)
Evaluate expression
Compare with each case
Match found?
NoThrow error or default
Yes
Return matched case value
End
The match expression evaluates a value, compares it to cases, and returns the matching case's result or a default.
Execution Sample
PHP
<?php
$color = 'red';
$result = match($color) {
  'red' => 'Stop',
  'green' => 'Go',
  default => 'Unknown'
};
echo $result;
This code matches the color variable to cases and prints the matching message.
Execution Table
StepExpression ValueCase CheckedMatch?ActionOutput
1'red''red'YesReturn 'Stop'
2'green'NoSkip
3defaultN/ANot reached
4End of matchStop
💡 Match found at case 'red', returned 'Stop', execution ends.
Variable Tracker
VariableStartAfter match
$colorundefined'red'
$resultundefined'Stop'
Key Moments - 2 Insights
Why does the match expression not continue checking other cases after a match?
Because match returns immediately when a case matches, as shown in step 1 of the execution_table where it returns 'Stop' and stops.
What happens if no case matches and there is no default?
Match throws an UnhandledMatchError error. This is not shown here because default is provided.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of $result after step 1?
A'Unknown'
B'Stop'
C'Go'
Dundefined
💡 Hint
Check the 'Action' and 'Output' columns at step 1 in the execution_table.
At which step does the match expression stop checking cases?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'Match?' column and when the action returns a value in the execution_table.
If $color was 'blue' instead of 'red', which case would be matched?
A'red'
B'green'
Cdefault
DNo match, error thrown
💡 Hint
Refer to the default case in the code and execution_table description.
Concept Snapshot
match(expression) {
  case1 => result1,
  case2 => result2,
  default => defaultResult
};

- Evaluates expression once
- Compares strictly (===) to cases
- Returns matched case value immediately
- Throws error if no match and no default
Full Transcript
The match expression in PHP 8 evaluates a given expression and compares it strictly to each case. When a match is found, it returns the corresponding value immediately and stops checking further cases. If no case matches and a default is provided, it returns the default value. Without a default, it throws an error. This example matches the variable $color to 'red', 'green', or default and returns a message accordingly.