A match expression is a new control structure in PHP 8 that allows you to compare a value against multiple conditions and return a result. It is similar to switch but more concise and returns a value.
Click to reveal answer
intermediate
How does match differ from switch in PHP?
Unlike switch, match is an expression that returns a value, supports strict type comparisons, does not allow fall-through, and requires all cases to be handled or a default to be provided.
Click to reveal answer
intermediate
What happens if no case matches and no default is provided in a match expression?
If no case matches and there is no default case, a UnhandledMatchError exception is thrown at runtime.
Click to reveal answer
beginner
Can a match expression have multiple conditions for a single case?
Yes, you can list multiple conditions separated by commas for a single case in a match expression, and if any condition matches, that case's value is returned.
Click to reveal answer
beginner
Write a simple match expression that returns 'Weekend' for 6 or 7, and 'Weekday' for 1 to 5.
B. Syntax error due to missing semicolon after match.
C. Missing default case causes UnhandledMatchError.
D. Variable $result is not assigned properly.
Solution
Step 1: Check for default case presence
The match expression lacks a default case for unmatched values.
Step 2: Understand consequences
If input does not match any case, PHP throws UnhandledMatchError.
Final Answer:
Missing default case causes UnhandledMatchError. -> Option C
Quick Check:
Always include default to avoid errors [OK]
Hint: Always add default case to handle unmatched values [OK]
Common Mistakes:
Assuming default case is optional
Thinking strings can't be used as match cases
Confusing syntax errors with runtime errors
5. You want to categorize a number into 'small', 'medium', or 'large' using a PHP 8 match expression. Which code correctly implements this logic for: - small: 1 or 2 - medium: 3 or 4 - large: any other number