A nested loop is a loop inside another loop. In PHP, nested loops are used to handle complex repetitive tasks such as iterating over multi-dimensional arrays, generating patterns, or working with combinations of values.
// Generic structure of a nested for loop
for (initialization; condition; increment) {
for (initialization; condition; increment) {
// inner loop logic
}
}
// Nested loop printing values of i and j
<?php
for ($i = 1; $i <= 3; $i++) {
for ($j = 1; $j <= 3; $j++) {
echo "i = $i, j = $j<br>";
}
}
?>
The outer for loop runs three times. For each iteration of the outer loop, the inner loop runs three times. This produces nine total combinations of $i and $j.
Adjust the sliders to see how the inner loop completes for every outer loop step.
Imagine a grid where rows represent $i and columns represent $j. Each cell is processed once by the inner loop for every row of the outer loop.
nested_loop.php