PHP Nesting Loops

Nesting Loops

nested loop is a loop within a loop, an inner loop within the body of an outer one.

Syntax:

//nested for
for (expr1; expr2; expr3) {
    for (expr1; expr2; expr3) {
        //statement;
    }
}

Normally nested for loop is used. while and do.. while not used.

Example:

<?php
for ($i = 1; $i < 5; $i++) {
    for ($j = 1; $j <= $i; $j++) {
        echo " * ";
    }
    echo '<br />';
}
?>

Output:

Tutorialik.com
*
* *
* * *
* * * *

Example:

<?php
for ($i = 1; $i < 5; $i++) {
    for ($j = $i; $j < 5; $j++) {
        echo " * ";
    }
    echo '<br />';
}
?>

Output:

Tutorialik.com
* * * * 
* * * 
* * 

Example:

<?php
for ($i = 1; $i < 5; $i++) {
    for ($j = $i; $j <= 5; $j++) {
        echo "&nbsp;"; // it will print blank space
    }
    for ($j = 1; $j <= $i; $j++) {
        echo " * ";
    }
    echo '<br />';
}
?>

Output:

Tutorialik.com
      * 
     * * 
    * * * 
   * * * * 


Share This Page to Download:

Share to Download

Share This Page on:


Ask Question

Loops