0
0
PHPprogramming~5 mins

Nested loop execution in PHP - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a nested loop in PHP?
A nested loop is a loop inside another loop. The inner loop runs completely every time the outer loop runs once.
Click to reveal answer
beginner
How many times will the inner loop run in this code?<br>
<?php
for ($i = 1; $i <= 3; $i++) {
  for ($j = 1; $j <= 2; $j++) {
    echo "$i,$j ";
  }
}
The inner loop runs 2 times for each of the 3 outer loop runs, so 3 × 2 = 6 times total.
Click to reveal answer
beginner
What is the output of this nested loop?<br>
<?php
for ($i = 1; $i <= 2; $i++) {
  for ($j = 1; $j <= 3; $j++) {
    echo $i * $j . ' ';
  }
}
The output is: 1 2 3 2 4 6 <br>Explanation: For i=1, j=1 to 3 outputs 1,2,3. For i=2, j=1 to 3 outputs 2,4,6.
Click to reveal answer
intermediate
Why do nested loops often have higher time complexity?
Because the inner loop runs completely for each iteration of the outer loop, the total steps multiply, making the program slower as input grows.
Click to reveal answer
beginner
How can you visualize nested loops in real life?
Imagine you have 3 boxes, and inside each box are 2 balls. You open each box (outer loop) and then pick each ball inside (inner loop).
Click to reveal answer
In PHP, if the outer loop runs 4 times and the inner loop runs 5 times, how many times does the inner loop execute in total?
A20
B9
C5
D4
What will this PHP code output?<br>
<?php
for ($i=1; $i<=2; $i++) {
  for ($j=1; $j<=2; $j++) {
    echo $i . $j . ' ';
  }
}
A1 2 2 2
B11 12 21 22
C12 21 22 11
DError
Which statement is true about nested loops?
AOuter loop runs inside inner loop
BInner loop runs once for all outer loop iterations
CInner loop runs completely for each outer loop iteration
DNested loops cannot be used in PHP
What is the time complexity of two nested loops each running n times?
AO(log n)
BO(n)
CO(1)
DO(n^2)
In PHP, which keyword is used to start a loop?
Afor
Bloop
Crepeat
Diterate
Explain how nested loops work in PHP with an example.
Think about a loop inside another loop and how many times the inner loop runs.
You got /4 concepts.
    Describe a real-life situation that helps you understand nested loops.
    Think about opening boxes and picking items inside.
    You got /3 concepts.