PHP Loops

Loops are used to repeatedly execute the same block of code as long as a condition is met. The basic concept behind a loop is to save time and effort by automating repetitive activities within a program. There are four different types of loops supported by PHP.


  • while
  • do...while
  • for
  • foreach

While Loop

The while statement loops around a block of code as long as the while statement's condition evaluates to true.


while(condition){
  // Your codes here
}



The loop in the example below begins with $i=1. As long as i is less than or equal to 3, the loop will keep running. Every time the loop runs, the i increases by one:


<?php
  $i = 1;
  while($i <= 3){
    $i++;
    echo "The number is " . $i . "<br>";
  }
?>



DoˇKwhile loop

The while loop is a version of the do-while loop in which the condition is evaluated at the end of each loop iteration A do-while loop runs a block of code once, then tests the condition; if the condition is valid, the assertion is repeated until the given condition is false.


do{
  // Your codes here
}
while(condition);



The example below shows how to build a loop that starts with $i=1. It will then add 1 to i and print the result. The condition is then evaluated, and the loop continues to run until i is less than or equal to 3.


<?php
$i = 1;
  do{
   $i++;
    echo "The number is " . $i . "<br>";
   }
  while($i <= 3);
?>



For loop

The for loop is a control structure that repeats a block of code as long as a condition is met. It's usually used to repeat a block of code a certain number of times.


for(initialization; condition; increment){
  // Your codes here
}



The example below shows how to create a loop that begins with $i=1. The loop will proceed until i equals or is less than 3. Every time the loop runs, the variable i will increase by one:


<?php
  for($i=1; $i<=3; $i++){
    echo "The number is " . $i . "<br>";
  }
?>



Foreach Loop

Iterating over arrays is done with the foreach loop.


  foreach($array as $value){
  // Your codes here
  }



The following example shows how to create a loop that prints the values of an array:


<?php
  $colors = array("Red", "Green", "Blue");

  // Loop through
  // colors array
  foreach($colors as $value){
    echo $value . "<br>";
  }
?>