0
0
PHPprogramming~20 mins

Switch statement execution in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Switch Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of switch with fall-through
What is the output of this PHP code?
PHP
<?php
$val = 2;
switch ($val) {
    case 1:
        echo "One ";
    case 2:
        echo "Two ";
    case 3:
        echo "Three ";
        break;
    default:
        echo "Default ";
}
?>
AOne Two Three
BTwo Three
CTwo
DDefault
Attempts:
2 left
💡 Hint
Remember that without break, cases fall through to the next.
Predict Output
intermediate
2:00remaining
Switch with strict type comparison
What will this PHP code output?
PHP
<?php
$value = '5';
switch ($value) {
    case 5:
        echo "Number 5";
        break;
    case '5':
        echo "String 5";
        break;
    default:
        echo "No match";
}
?>
ANumber 5
BString 5
CNo match
DError
Attempts:
2 left
💡 Hint
PHP switch uses loose comparison (==), not strict (===).
🔧 Debug
advanced
2:00remaining
Identify the error in switch syntax
Which option contains a syntax error in the switch statement?
A
&lt;?php
switch ($x) {
    case 1:
        echo "One";
        break;
    default
        echo "Default";
}
?&gt;
B
&lt;?php
switch ($x) {
    case 1:
        echo "One";
        break;
    default:
        echo "Default";
}
?&gt;
C
&lt;?php
switch ($x) {
    case 1:
        echo "One";
        break;
    case 2:
        echo "Two";
        break;
}
?&gt;
D
&lt;?php
switch ($x) {
    case 1:
        echo "One";
        break;
    case 2:
        echo "Two";
        break;
    default:
        echo "Default";
}
?&gt;
Attempts:
2 left
💡 Hint
Check the syntax for the default case.
Predict Output
advanced
2:00remaining
Switch with multiple cases and no breaks
What is the output of this PHP code?
PHP
<?php
$val = 1;
switch ($val) {
    case 0:
    case 1:
    case 2:
        echo "Low ";
    case 3:
        echo "Mid ";
        break;
    default:
        echo "High ";
}
?>
AMid
BLow
CLow Mid
DHigh
Attempts:
2 left
💡 Hint
Cases 0,1,2 share the same block without breaks.
🧠 Conceptual
expert
2:00remaining
Behavior of switch with non-scalar expression
What happens when you use an array as the switch expression in PHP like this?
PHP
<?php
$arr = [1, 2];
switch ($arr) {
    case [1, 2]:
        echo "Match";
        break;
    default:
        echo "No match";
}
?>
AOutputs 'Match' because arrays are compared by value.
BOutputs 'No match' because switch cannot compare arrays.
CCauses a fatal error due to invalid switch expression.
DRaises a warning and outputs 'No match'.
Attempts:
2 left
💡 Hint
PHP switch uses loose comparison but arrays in switch cause warnings.