Nested loops in PHP explained

Published: 19 March 2025
on channel: PHP Explained
100
2

Nested loops means one loop contains another loop.

There are four ideal loop structure available in PHP and these are while, do while, for, and foreach loop.

Any of these four types of loops can contain each other to form nested loop. There is no limitation of nested number of loops.

Let's explain with an example.

Here we are using for loop.
First for loop called outer for loop contains another for loop called inner for loop.

Outer loop consists of variable i and iterates for 10 times.

Inner loop consists of variable j and iterates for 10 times also.

For one iteration of the outer loop, the inner loop iterates 10 times. So, all together 10 times outer multiplied by 10 times inner iterations, equal to 100, hence the loops are iterating for 100 times.

for ($i = 1; $i lt;= 10; $i++)
{
for ($j = 1; $j lt;= 10; $j++)
{
echo $i . " " . $j . "\n";
}
}


On this page of the site you can watch the video online Nested loops in PHP explained with a duration of hours minute second in good quality, which was uploaded by the user PHP Explained 19 March 2025, share the link with friends and acquaintances, this video has already been watched 100 times on youtube and it was liked by 2 viewers. Enjoy your viewing!