PHP For Loop

PHP For Loop is Control Statement which can be used to run block of code for the specified number of times.
Syntax:
   for(Initialization; Condition; Increment/Decrement){  
        //code to be executed for For Loop  
    } 
Parameters:
    1. Initialization => Initialize the loop counter value
    2. Condition => Evaluate each iteration value. The loop continuously executes until the condition is false. If TRUE, the loop execution continues, otherwise the execution of the loop ends.
    3. Increment/Decrement => It increments or decrements loop counter value.

Example :
   <?php
        for ($i = 0; $i <= 5; $i++) {
          echo "The number is: $i <br>";
        }
     ?>
     where $i = 0 - counter starts value at 0.
              $i <= 5 - Loop will be executed until conter will reach at value 5.
              $i++ - Conter value will be incremented  by value 1.
Output:
     The number is: 1
     The number is: 2
     The number is: 3
     The number is: 4
     The number is: 5

   PHP Nested For Loop :
   If For loop inside for loop in PHP, it is called as nested for loop. The inner for loop executes only when the outer for loop condition is true.
    Example : Displays a pyramid of stars.
    <?
    for($i=0;$i<=6;$i++)
    {
        
        for($j=0;$j<=$i;$j++)
        {
            echo(" * ");
        }
        echo("<br />");
    
   }
 ?>
Outputs :
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

33071