Looping Statements in PHP

By | April 6, 2020

In this tutorial, we will learn Looping Statements in PHP. Looping statements help us to run a piece of code again and again. For example, you want to show 1 to 100 on your page. IN normal case you have to write echo 100 times with the number to show 1 to 100 on the web page. But with the help of a loop, you can do this task very easily by writing echo for only once. There are three looping statements in PHP.

  • for loop
  • while loop
  • do-while loop

Now we will learn each looping statement in detail.

for loop:

for loop is used to run a piece of code for the certain number of times. For loop take three expressions. In the first expression, we initialize a variable after that in the second expression we write and condition and in the last expression we increment or decrement the variable. To understand it you can check the following syntax to define for loop in C.

for (initializationStatement; testExpression; updateStatement)
{
    // statements inside the body of for loop
}

To understand the flow of the for loop in PHP. You can check the following flow chart.

Looping Statements in PHP

Check this example. In this example, we will write 1 to 10 using for loop.

Example Program:

<?php
   for($i=1;$<=10;$i++){
      echo "$i\n";
   }
?>

while loop:

If you want to run a piece of code again and again until a certain condition is true. You can use while loop. while loop takes only a single expression which is conditional expression. Check out the syntax to define while loop in PHP.

while(condition){
    //body of the loop
  }

To understand the flow of the while loop. Please checkout the following flow chart diagram.

Looping statements in PHP

Here is Example of while loop.

Example Program:

<?php
   $i=1;
   while(i<=10){
      echo "$i\n";
      $i++;
   }
?>

do while loop: 

The do-while loop is the same as while loop but there is a small difference. In case of the false condition in the first iteration of while loop, Body of while loop would not run. But in case of the do-while loop. It will run. because it checks condition after running the body of the loop. Check out the syntax to define the do-while loop in PHP.

do{
   //body of the loop
}while(condition)

To understand the flow of the do while loop. Please check out the following flow chart.

Looping statements in PHP

Example Program:

<?php
   $i=1;
   do{
      echo "Hello";
   }while(i!=1)
?>