Various types of Loops in PHP

Loop use to execute the same block of code single or multiple times in the program.

With this, you can do more with less number of codes.

There are various types of loops –

  • while
  • do-while
  • for
  • foreach

Various types of Loops in PHP


Contents

  1. while
  2. do-while
  3. for
  4. foreach
  5. Conclusion

1. while

  • Loop through a block of code as long as the specified condition is true.
  • In the while loop, it first checks the condition if the specified condition is true then the block of statements executes.

Syntax –

while(condition){

//  Executable code

}

Example-

<html>

<body> 
      <?php 
           $count = 1; 
           while($count<=10){ 
                 $count++; 
           } 
           echo $count; 
       ?> 
</body>

</html>

Output –

11

2. do-while

In do-while it first executes the statements then checks the condition if the condition is true then loop executes until the specified condition is not false.

Syntax –

do{

// Executable code

}while(condition);

Example-

Here, the condition is false but the loop executes one time.

<html>

<body>

     <?php

          $count = 1;

          do{

              $count++;

          }while($count<=10);

          echo $count;

      ?>

</body>

</html>

Output –

11

3. for

Loop through a block of code a specified number of times. In for loop, you can initialize, specify the condition and define the increment/decrement of the variable in the same line.

Syntax –

for(initialize;condition;increment/decrement){

// Executable code

}

Example –

<html>

<body>
      <?php
          for($count=1;$count<=10;$count++){

          }
          echo $count;
      ?>
</body>

</html>

Output –

11

4. foreach

foreach loop works with arrays, objects and it loops through each key/value in the array/object.

Syntax –

foreach($array as $value){

// Executable code

}

Example –

  • foreach with value
<html>

<body>

     <?php
          $values = array("one","two","three","four");
          foreach($values as $value){
               echo "value = ".$value."<br/>";
          }
     ?>

</body>

</html>

Output –

value = one
value = two
value = three
value = four
  • foreach with key and value
<html>

<body>

     <?php

         $values = array("one"=>1,"two"=>2,"three"=>3);

         foreach($values as $key=>$value){

            echo "key : ".$key." , value : ".$value."<br/>";

         }

     ?>

</body>

</html>

Output –

key : one , value : 1
key : two , value : 2
key : three , value : 3

5. Conclusion

Use a loop to traverse on the Array or Object, and execute statements according to the condition.

If you found this tutorial helpful then don't forget to share.

Leave a Comment