Introduction
Nested loops let you repeat actions inside other repeated actions. This helps when you work with tables or grids.
Nested loops let you repeat actions inside other repeated actions. This helps when you work with tables or grids.
<?php for (initialization; condition; increment) { for (initialization; condition; increment) { // code to repeat } } ?>
<?php for ($i = 1; $i <= 3; $i++) { for ($j = 1; $j <= 2; $j++) { echo "$i,$j\n"; } } ?>
<?php for ($row = 1; $row <= 2; $row++) { for ($col = 1; $col <= 3; $col++) { echo "*"; } echo "\n"; } ?>
This program prints a 3 by 3 multiplication grid. Each row shows multiples of the row number.
<?php // Print a 3x3 grid of numbers for ($i = 1; $i <= 3; $i++) { for ($j = 1; $j <= 3; $j++) { echo $i * $j . " "; } echo "\n"; } ?>
Remember to add a newline after the inner loop to separate rows.
Nested loops can slow down your program if they run many times, so use them carefully.
Nested loops run one loop inside another to handle repeated tasks in layers.
The inner loop finishes all its cycles for each single cycle of the outer loop.
They are useful for working with tables, grids, and pairs of data.
for ($i = 0; $i < 2; $i++) {
for ($j = 0; $j < 3; $j++) {
// code
}
}for loop in PHP?for ($i = 1; $i <= 2; $i++) {
for ($j = 1; $j <= 3; $j++) {
echo $i * $j . ' ';
}
}for ($i = 0; $i < 3; $i++) {
for ($j = 0; $j < 2; $i++) {
echo $i . $j . ' ';
}
}?
Pass the test and this pattern moves unknown