PHP

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
      * 
     * * 
    * * * 
   * * * * 



Subscribe us on Youtube

Share This Page on

Question


PhpOnweb | 27-Aug-2018 05:41:13 pm

Hi dude, i have also find out one good example Loops – PHP Example


Ask Question