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.

In PHP, 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

 


1. while

  • Loop through a block of code as long as the specified condition is true.
  • In the while loop, it first check the condition if 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 check the condition if the condition is true then loop executes until specified condition is not false.

Syntax –

do{

// Executable code

}while(condition);

Example-

<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, we can initialize, specify the condition and define 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

Related Post

Spread the love
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Be First to Comment

Leave a Reply

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