Loops in PHP ( for , while , do while , foreach)

Loops 

     

        A loop is a piece of code in a script automatically repeats . One complete execution of all statement within a loop is called an " iteration " or "pass" .
The length of a loop is a controlled by a conditional test made within the loop 

In PHP there are these four type of loop structure 
 
1 . for loop - performs a specified number of iteration .

2 . while loop - performs iteration only while a test made at the start of each                          iteration evaluates as TRUE

3 . do while loop - performs iterations only while a test made at the end of each                     iteration evaluates as TRUE 

4 . foreach loop - performs iteration through each element of an array 


Syntax 

     for ( initializer ; test-expression ; increment )
          {
              statement-to-be-executed
           }


PHP Programs

<?php
for($i=1$i<4;$i++)
  {
     echo " outer loop iteration $i";
    for($j=1$j<4$j++)
    {
        echo "Inner loop iteration $j";
    }
  }

   
?>


Output




While Loop 

      while loop is an alternative to the for loop  

Syntax
      initializer
      while (test-expression)
          {
              statement-to-be-executed ; incrementer
           }

PHP Programs

<?php
    $number = array(10,20,30);

         // While Loop 
    echo "While Loop";
    $i=0;
    while($i<3)
     {
         echo " <dd>Element $i = $number[$i]";
         $i++;
     }


        // Do While Loop 
     echo " Do While Loop ";
     $i=0;
     do
      {
          echo " <dd>Element $i = $number[$i]";
          $i++ ;
      }
      while($i<3)

?>
    
Output



   
for loop 

   for loop performs three iteration 

 PHP Programs 
<?php
    for ($i=1 ; $i<4 ; $i++)
      {
          for($j=1 ; $j<4 ; $j++)
            {
                if($i==2 && $j==1)
                  {
                      echo " Running i =$i and j=$j";
                  }
            }
      }
?>


Output 


Comments

Popular posts from this blog

Switching Branches