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?
✗ Incorrect
The inner loop runs 5 times for each of the 4 outer loop runs, so 4 × 5 = 20 times.
What will this PHP code output?<br>
<?php
for ($i=1; $i<=2; $i++) {
for ($j=1; $j<=2; $j++) {
echo $i . $j . ' ';
}
}✗ Incorrect
The output is '11 12 21 22 ' because for i=1, j=1 and 2 prints 11 and 12; for i=2, j=1 and 2 prints 21 and 22.
Which statement is true about nested loops?
✗ Incorrect
The inner loop runs fully every time the outer loop runs once.
What is the time complexity of two nested loops each running n times?
✗ Incorrect
Two nested loops each running n times result in O(n × n) = O(n^2) time complexity.
In PHP, which keyword is used to start a loop?
✗ Incorrect
The 'for' keyword is used to start a for loop in PHP.
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.