PHP - Nested for Loops


When you nest one loop inside another, the inner loop runs through all its iterations first.

Then the outer loop iterates, causing the inner loop to run through all its iterations again, and so on.

Here's a simple example of nested looping:



         for ( $tens = 0; $tens  <  10; $tens++ ) {
           for ( $units = 0; $units  <  10; $units++ ) {
             echo $tens . $units . " \n ";
           }/*from  w  w  w.ja v  a2s  . c  om*/


Here, the code displays all the integers from 0 to 99.

It sets up two loops: an outer "tens" loop and an inner "units" loop.

Each loop counts from 0 to 9.

For every iteration of the "tens" loop, the "units" loop iterates 10 times.

With each iteration of the "units" loop, the current number is displayed by concatenating the $units value onto the $tens value.

The outer loop iterates 10 times, whereas the inner loop ends up iterating 100 times: 10 iterations for each iteration of the outer loop.

Related Topic