PHP – Loop Types

Loops in PHP are used to execute the same block of code a specified number of times. PHP supports following four loop types.

  • for − loops through a block of code a specified number of times.
  • while − loops through a block of code if and as long as a specified condition is true.
  • do…while − loops through a block of code once, and then repeats the loop as long as a special condition is true.
  • foreach − loops through a block of code for each element in an array.

    The for loop statement

The for statement is used when you know how many times you want             to execute a statement or a block of statements.

for loop in Php

Syntax for for loop:-

for (initialization; condition; increment)
{ code to be executed; }

Example:-

<html>

<body>

<?php

 

 

for( $i = 0; $i<5; $i++ )

{

echo “$i”;

}

echo “<br>”;

 

?>

</body>

</html>

The while loop statement

The while statement will execute a block of code if and as long as a test expression is true.

If the test expression is true then the code block will be executed. After the code has executed the test expression will again be evaluated and the loop will continue until the test expression is found to be false.

Syntax for while loop:-

while (condition)
{ code to be executed; }

Example:

<html>
   <body>
   
      <?php
         $i = 0;
         $num = 50;
         
         while( $i < 10) {
            $num--;
            $i++;
         }
         
         echo ("Loop stopped at i = $i and num = $num" );
      ?>
      
   </body>
</html>

Output will be:

Loop stopped at i = 10 and num = 40

The do…while loop statement

The do…while statement will execute a block of code at least once – it then will repeat the loop as long as a condition is true.

Syntax for do-while loop:-

do { code to be executed; } while (condition);

Example:

<html>
   <body>
   
      <?php
         $i = 0;
         $num = 0;
         
         do {
            $i++;
         }
         
         while( $i < 10 );
         echo ("Loop stopped at i = $i" );
      ?>
      
   </body>
</html>

The foreach loop statement

The foreach statement is used to loop through arrays. For each pass the value of the current array element is assigned to $value and the array pointer is moved by one and in the next pass next element will be processed.

Syntax for for-each loop:-

foreach (array as value)
{ code to be executed; }

Example:

<html>
   <body>
   
      <?php
         $array = array( "a", "b", "u", "g", "f");
         
         foreach( $array as $value ) {
            echo "Value is $value <br />";
         }
      ?>
      
   </body>
</html>

Output will be:
Value is a
Value is b
Value is u
Value is g
Value is f
 

Leave a Reply

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