0
0
PHPprogramming~20 mins

Nested loop execution in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Nested Loop Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of nested for loops with break
What is the output of this PHP code?
PHP
<?php
for ($i = 1; $i <= 3; $i++) {
    for ($j = 1; $j <= 3; $j++) {
        if ($j == 2) {
            break;
        }
        echo "$i$j ";
    }
}
?>
A12 22 32
B11 12 21 22 31 32
C11 12 13 21 22 23 31 32 33
D11 21 31
Attempts:
2 left
💡 Hint
Remember that break exits the inner loop immediately when condition is met.
Predict Output
intermediate
2:00remaining
Output of nested while loops with continue
What is the output of this PHP code?
PHP
<?php
$i = 1;
while ($i <= 2) {
    $j = 1;
    while ($j <= 3) {
        if ($j == 2) {
            $j++;
            continue;
        }
        echo "$i$j ";
        $j++;
    }
    $i++;
}
?>
A11 13 12 21 23 22
B11 13 21 23
C11 12 13 21 22 23
D12 22
Attempts:
2 left
💡 Hint
The continue skips printing when $j == 2 but increments $j before continuing.
🧠 Conceptual
advanced
2:00remaining
Number of iterations in nested loops
How many times will the innermost statement execute in this PHP code?
PHP
<?php
for ($a = 0; $a < 4; $a++) {
    for ($b = 0; $b < 3; $b++) {
        for ($c = 0; $c < 2; $c++) {
            // innermost statement
        }
    }
}
?>
A24
B9
C12
D6
Attempts:
2 left
💡 Hint
Multiply the number of iterations of each loop.
🔧 Debug
advanced
2:00remaining
Identify the error in nested loops
What error will this PHP code produce?
PHP
<?php
for ($x = 0; $x < 3; $x++) {
    for ($y = 0; $y < 3; $y++)
        echo "$x$y ";
}
?>
ANo error, outputs '000102...222'
BParse error: syntax error, unexpected '}'
CFatal error: Maximum execution time exceeded
DWarning: Undefined variable
Attempts:
2 left
💡 Hint
Check the braces carefully for matching pairs.
🚀 Application
expert
3:00remaining
Output of nested loops with conditional break and continue
What is the output of this PHP code?
PHP
<?php
for ($i = 1; $i <= 3; $i++) {
    for ($j = 1; $j <= 3; $j++) {
        if ($i == $j) {
            continue;
        }
        if ($j == 3) {
            break;
        }
        echo "$i$j ";
    }
}
?>
A12 13 21 31 32
B12 21 23 31 32
C12 21 31 32
D12 13 21 23 31
Attempts:
2 left
💡 Hint
Remember continue skips current iteration, break exits inner loop.