PHP – Loops – while – do…while – for – foreach

while

<?php 
$x=1; 
while($x<=5) // It executes the code as long as the specified condition is true.
  {
  echo "The number is: $x <br>";
  $x++;
  } 
?>

do…while

<?php 
$x=1; 
do
  {
  echo "The number is: $x <br>";
  $x++;
  }
while ($x<=5)  // It executes the code as long as the specified condition is true.
?>

NOTICE:
while -> 1. condition verification 2. code execution
do…while -> 1. code execution 2. condition verification

for

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

foreach

The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.

<?php 
$colors = array("red","green","blue","yellow"); 
foreach ($colors as $value)
  {
  echo "$value <br>";
  }
?>