Nested Loops in PHP
Loops, which you already know how to work with, can be nested inside each other. For example, let's solve the following problem: display the string:
111222333444555666777888999
You can't manage with one loop here - you need to run
two loops nested inside each other: the first
loop will iterate over numbers (first 1
,
then 2
, then 3
and so on up to 9
),
and the second loop will repeat these numbers three times.
Let's implement it:
<?php
for ($i = 1; $i <= 9; $i++) {
for ($j = 1; $j <= 3; $j++) {
echo $i;
}
}
?>
Pay attention: the first loop has a counter
$i
, the second one $j
, and if there is
a third loop - its counter will be
the variable $k
. These are standard generally accepted
names, you should use them.
Using two nested loops, display the following string:
111222333444555666777888999
Using two nested loops, display the following string:
11 12 13 21 22 23 31 32 33