0
0
PHPprogramming~20 mins

Match expression (PHP 8) - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
PHP 8 Match Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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;
ATwo
BOne
CThree
DOther
Attempts:
2 left
💡 Hint
Look at the value of $input and which case it matches.
Predict Output
intermediate
2: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;
ALetter in x-z
BOther letter
CLetter in a-c
DSyntax error
Attempts:
2 left
💡 Hint
Check which group the input letter belongs to.
Predict Output
advanced
2: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;
AInteger one
BTypeError
COther
DString one
Attempts:
2 left
💡 Hint
Match uses strict comparison (===), so type matters.
Predict Output
advanced
2: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;
AOne
BUnhandledMatchError
CThree
DTwo
Attempts:
2 left
💡 Hint
What if no case matches and no default is given?
🧠 Conceptual
expert
3: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;
A3
B2
C4
D0
Attempts:
2 left
💡 Hint
Evaluate the expression for the matching case.