Bird
0
0

What is the error in this nested loop PHP code?

medium📝 Debug Q7 of 15
PHP - Loops
What is the error in this nested loop PHP code?
for ($x = 1; $x <= 4; $x++) {
for ($y = 1; $y <= 3; $y++) {
echo $x + $y . ' ';
$x++;
}
}
AThe outer loop variable <code>$x</code> is incorrectly incremented inside the inner loop.
BThe inner loop condition should be <code>$y < 3</code> instead of <code>$y <= 3</code>.
CThe echo statement should concatenate strings instead of adding numbers.
DThere is no error; the code runs correctly.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze loop variables

    The outer loop variable $x controls the main iterations.
  2. Step 2: Check increments

    Incrementing $x inside the inner loop causes unexpected behavior and skips iterations.
  3. Step 3: Correct increment placement

    $x++ should only be incremented in the outer loop control statement.
  4. Final Answer:

    The outer loop variable $x is incorrectly incremented inside the inner loop. identifies the error correctly.
  5. Quick Check:

    Outer loop variable must not be changed inside inner loop [OK]
Quick Trick: Increment outer loop variable only in outer loop header [OK]
Common Mistakes:
  • Incrementing outer loop variable inside inner loop
  • Confusing loop variables
  • Infinite loops due to wrong increments

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes