codegurukool.com · Free coding tutorials & online compiler

Home › PHP Tutorial › PHP loops

PHP loops

Repeat code with for, while and foreach.

for counts, while repeats while a condition holds, and foreach walks through an array.

Example code

<?php
for ($i = 1; $i <= 5; $i++) {
  echo $i . " ";
}
echo PHP_EOL;
$n = 3;
while ($n > 0) {
  echo $n-- . " ";
}
echo PHP_EOL;
foreach (["red", "green"] as $c) {
  echo $c . PHP_EOL;
}
?>

Run this code in the online editor

← PHP switch and matchPHP functions →