PHP Loops

PHP loops are used to execute a certain block of code, while the specific condition is true.

If you want run over / execute  same set  of codes in your page you can use PHP loops.

In PHP we are having 4 different types of looping statement:

  • while
  • do … while
  • for
  • foreach

For your reference below some examples are given.

The PHP while loop:

<?php
$i = 2;
while($i <= 6){
   echo $i."<br />";
   $i++;
}
?>

Output:

2
3
4
5
6

The PHP do…while loop:

<?php 
$i=2; 
do
  {
  echo "The current value is: $i <br>";
  $x++;
  }
while ($i<=4)
?>
Output:

The current value is: 2
The current value is: 3
The current value is: 4

The PHP for loop:

<?php 
for ($i=0; $i<=10; $i++)
  {
  echo "The current value is: $x <br>";
  } 
?>

The PHP foreach loop:

<?php 
$students = array("Jhon","Victor","Ram","Vijay"); 
foreach ($students as $value)
  {
  echo "$value <br>";
  }
?>