Bird
0
0

Given this nested loop, how can you modify it to stop all loops when $k == 1?

hard📝 Application Q8 of 15
PHP - Loops

Given this nested loop, how can you modify it to stop all loops when $k == 1?

for ($i = 0; $i < 3; $i++) {
    for ($j = 0; $j < 3; $j++) {
        for ($k = 0; $k < 3; $k++) {
            if ($k == 1) {
                // What break statement stops all loops here?
            }
            echo "$i$j$k ";
        }
    }
}
Acontinue 3;
Bbreak 2;
Cbreak 3;
Dbreak;
Step-by-Step Solution
Solution:
  1. Step 1: Count nested loops

    There are three nested loops: $i, $j, and $k.
  2. Step 2: Use break with correct level

    To stop all three loops when $k == 1, use break 3; inside the innermost loop.
  3. Final Answer:

    break 3; -> Option C
  4. Quick Check:

    Break 3 exits all three loops [OK]
Quick Trick: Use break n; where n = number of nested loops to exit all [OK]
Common Mistakes:
  • Using break 2; exits only two loops
  • Using break; exits only innermost loop
  • Using continue instead of break

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes