Challenge - 5 Problems
PHP 8 Match Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a simple match expression
What is the output of the following PHP code using a match expression?
PHP
<?php $input = 2; $result = match($input) { 1 => 'One', 2 => 'Two', 3 => 'Three', default => 'Other' }; echo $result;
Attempts:
2 left
💡 Hint
Look at the value of $input and which case it matches.
✗ Incorrect
The match expression compares $input to each case. Since $input is 2, it matches the case 2 and returns 'Two'.
❓ Predict Output
intermediate2:00remaining
Match expression with multiple conditions
What will this PHP code output when using a match expression with multiple conditions in one arm?
PHP
<?php $input = 'b'; $result = match($input) { 'a', 'b', 'c' => 'Letter in a-c', 'x', 'y', 'z' => 'Letter in x-z', default => 'Other letter' }; echo $result;
Attempts:
2 left
💡 Hint
Check which group the input letter belongs to.
✗ Incorrect
The input 'b' matches the first arm with multiple conditions 'a', 'b', 'c', so it returns 'Letter in a-c'.
❓ Predict Output
advanced2:00remaining
Match expression with strict type comparison
What is the output of this PHP code using match expression with strict type comparison?
PHP
<?php $input = '1'; $result = match($input) { 1 => 'Integer one', '1' => 'String one', default => 'Other' }; echo $result;
Attempts:
2 left
💡 Hint
Match uses strict comparison (===), so type matters.
✗ Incorrect
The input is a string '1', so it matches the case '1' (string) and returns 'String one'. The integer 1 case does not match because types differ.
❓ Predict Output
advanced2:00remaining
Match expression without default arm
What happens when this PHP code runs a match expression without a default arm and no case matches?
PHP
<?php $input = 5; $result = match($input) { 1 => 'One', 2 => 'Two', 3 => 'Three' }; echo $result;
Attempts:
2 left
💡 Hint
What if no case matches and no default is given?
✗ Incorrect
If no case matches and there is no default arm, PHP throws an UnhandledMatchError exception.
🧠 Conceptual
expert3:00remaining
Behavior of match expression with expressions as arms
Consider this PHP code using match expression with expressions as arms. What is the output?
PHP
<?php $input = 3; $result = match($input) { 1 => 1 + 1, 2 => 2 * 2, 3 => strlen('abc'), default => 0 }; echo $result;
Attempts:
2 left
💡 Hint
Evaluate the expression for the matching case.
✗ Incorrect
The input is 3, so the matching arm is 3 => strlen('abc'). strlen('abc') returns 3, so the output is 3.