PHP For loop

PHP For loop

PHP For loop


The for loop is the most difficult loop in PHP.

Diagram of for loop:

for



Syntax of for loop:

<?php
   for (initialization counter; condition; increment)
   {
       //code to be executed
   }
?>

The For statement takes three expressions inside its parentheses, separated by semicolons. When the For loop executes, happens the following:

  • Set a counter variable to some initial value.
  • Check to see if the condition is true.
  • Execute the code within the loop.
  • Increment a counter at the end of each iteration through the loop.
<?php
   for ($i = 0;  $i < 10; $i++)
   {
       echo $i . " " ;
   }
 
   // output 0 1 2 3 4 5 6 7 8 9 
   
?>

Each of these expressions may be empty. If the conditions are not present, then the cycle continues indefinitely, in this case, we need to finish the cycle using break statement .

<?php
   for ($i = 0;  ; $i++)
   {
       if($i == 9)
       {
           break;
       }
       echo $i . " " ;
   }
 
   // output 0 1 2 3 4 5 6 7 8 9 
   
?>

or

<?php
   $i = 0;
   for ( ;; )
   {
       if($i == 9)
       {
           break;
       }
       echo $i . " " ;
       $i ++ ;
   }
 
   // output 0 1 2 3 4 5 6 7 8 9 
   
?>
Reactions

Post a Comment

0 Comments

close