0
0
PHPprogramming~20 mins

While loop execution model in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
While Loop Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this PHP while loop?
Consider the following PHP code snippet. What will it print?
PHP
<?php
$i = 3;
while ($i > 0) {
    echo $i . " ";
    $i--;
}
?>
A3 2 1
B1 2 3
C3 2 1 0
D0 1 2 3
Attempts:
2 left
💡 Hint
Remember the loop runs while the condition is true and $i decreases each time.
Predict Output
intermediate
2:00remaining
How many times does this while loop run?
Look at this PHP code. How many times will the loop body execute?
PHP
<?php
$count = 0;
$num = 5;
while ($num > 2) {
    $count++;
    $num--;
}
echo $count;
A5
B4
C3
D2
Attempts:
2 left
💡 Hint
Count how many times $num is greater than 2 before the loop stops.
🔧 Debug
advanced
2:00remaining
Identify the error in this while loop code
This PHP code is supposed to print numbers 1 to 5 but causes an error or unexpected behavior. What is the problem?
PHP
<?php
$i = 1;
while ($i <= 5)
    echo $i . " ";
    $i++;
?>
AVariable $i is not initialized before the loop
BThe condition uses <= instead of <, causing an off-by-one error
CMissing semicolon after echo statement
DThe increment $i++ is outside the loop block, causing an infinite loop
Attempts:
2 left
💡 Hint
Check which statements are inside the loop and which are not.
🧠 Conceptual
advanced
2:00remaining
What happens if the while loop condition is false initially?
Consider this PHP code snippet. What will be the output?
PHP
<?php
$x = 0;
while ($x > 0) {
    echo "Looping ";
    $x--;
}
echo "Done";
APrints only 'Done'
BPrints 'Looping ' multiple times then 'Done'
CPrints nothing
DCauses an infinite loop
Attempts:
2 left
💡 Hint
Think about whether the loop body runs if the condition is false at start.
Predict Output
expert
2:00remaining
What is the final value of $result after this while loop?
Analyze the PHP code below and find the value of $result after the loop finishes.
PHP
<?php
$n = 4;
$result = 1;
while ($n > 0) {
    $result *= $n;
    $n--;
}
echo $result;
A10
B24
C0
D1
Attempts:
2 left
💡 Hint
This loop multiplies $result by $n each time, decreasing $n from 4 to 1.