R
Rishtaara
PHP Fundamentals
Lesson 8 of 32Article17 min

Loops — While, Do...While, For, Foreach

while repeats while a condition is true. do...while runs the body at least once, then checks the condition.

While and Do...While

while repeats while a condition is true. do...while runs the body at least once, then checks the condition.

Real-life example: while is "keep filling cups while water remains." do...while is "serve one cup, then check if more guests want water."

while and do...while
<?php
$i = 1;
while ($i <= 3) {
  echo "Lesson $i\n";
  $i++;
}

$j = 1;
do {
  echo "At least once: $j\n";
  $j++;
} while ($j <= 1);
?>

For loop

for(init; condition; increment) is ideal when you know how many times to repeat — like looping lesson numbers 1 to 32.

Real-life example: A for loop is climbing stairs — start at step 1, stop at step 10, go up one each time.

for loop
<?php
for ($lesson = 1; $lesson <= 5; $lesson++) {
  echo "PHP Lesson $lesson\n";
}

// Nested loop — multiplication table row
for ($x = 1; $x <= 3; $x++) {
  for ($y = 1; $y <= 3; $y++) {
    echo "$x x $y = " . ($x * $y) . "\n";
  }
}
?>

Foreach — looping arrays

foreach walks through every item in an array. Use as $value or as $key => $value for associative arrays.

Real-life example: foreach is reading every name on a class attendance sheet one by one.

foreach examples
<?php
$topics = ["Syntax", "Forms", "MySQL", "OOP"];

foreach ($topics as $topic) {
  echo "- $topic\n";
}

$user = ["name" => "Asha", "role" => "student"];
foreach ($user as $key => $value) {
  echo "$key: $value\n";
}
?>

Break and Continue

break exits the loop early. continue skips the rest of the current iteration and moves to the next one.

Real-life example: break is leaving the queue when you find your friend. continue is skipping one bad apple and checking the next.

break and continue
<?php
for ($i = 1; $i <= 10; $i++) {
  if ($i === 5) continue; // skip 5
  if ($i === 8) break;    // stop at 8
  echo "$i ";
}
?>