Loops

Loops help you repeat actions: count numbers, iterate arrays, read files line by line, paginate records, etc. In PHP you’ll use for, while, do…while, and foreach. You can also break or skip iterations, and use generators to stream data efficiently.

LoopBest forNotes
forKnown count/index iterationAll loop parts inline (init; condition; step)
whileRepeat while condition trueCheck before each iteration
do…whileRun at least onceCheck after iteration
foreachArrays/TraversablesSafest & most readable for collections

1) for

<?php
  for ($i = 1; $i <= 5; $i++) {
    echo "Count: $i\n";
  }
?>

Multiple expressions

<?php
  for ($i=0, $j=10; $i<5; $i++, $j--) {
    echo "$i $j\n";
  }
?>

2) while

<?php
  $n = 3;
  while ($n > 0) {
    echo "n=$n\n";
    $n--;
  }
?>

3) do…while (runs at least once)

<?php
  $pwdOk = false;
  do {
    echo "Try login once\n";
  } while ($pwdOk);
?>

4) foreach (arrays & traversables)

By value (default)

<?php
  $nums = [10,20,30];
  foreach ($nums as $n) {
    echo $n; // 10 20 30
  }
?>

With keys

<?php
  $user = ["name"=>"Sonu", "age"=>25];
  foreach ($user as $key => $value) {
    echo "$key: $value\n";
  }
?>

By reference (modifies original)

<?php
  $arr = ["a", "b"];
  foreach ($arr as &$v) {
    $v = strtoupper($v);
  }
  // IMPORTANT: unset reference to avoid side-effects later
  unset($v);
  var_dump($arr); // ["A","B"]
?>
Warning: When using & in foreach, always unset($v) afterwards to break the reference.

5) break & continue

<?php
  for ($i=1; $i<=10; $i++) {
    if ($i == 3) continue; // skip 3
    if ($i == 7) break;    // stop at 6
    echo $i;
  }
?>

Breaking out of nested loops

Use numeric argument or labels to break multiple levels.

<?php
  outer: for ($i=1; $i<=3; $i++) {
    for ($j=1; $j<=3; $j++) {
      if ($i*$j == 4) {
        break 2; // break two levels
        // or: break outer;
      }
      echo "$i,$j\n";
    }
  }
?>

6) Iteration Tips

  • Prefer foreach for arrays/maps — clearer and safer than manual indexes.
  • When you need the index/key, use foreach ($arr as $k => $v).
  • Need to modify original values? Use &$v and remember unset($v).
  • For large datasets, process in batches or use generators to reduce memory.
  • Avoid changing the array you’re iterating over (push/pop) — iterate a copy or collect changes.

7) Generators with yield (memory friendly)

Generators let you iterate results one by one without building big arrays in memory.

<?php
  function countUp($max) {
    for ($i=1; $i<=$max; $i++) {
      yield $i;
    }
  }
  foreach (countUp(5) as $n) {
    echo $n;
  }
?>

Generator with keys

<?php
  function lines($path) {
    $h = fopen($path, 'r');
    $i = 0;
    while (($line = fgets($h)) !== false) {
      yield $i++ => rtrim($line, "\r\n");
    }
    fclose($h);
  }
  foreach (lines('/path/to/file.txt') as $num => $text) {
    echo ($num+1) . ": $text\n";
  }
?>

8) Common Pitfalls

IssueWhy it happensFix
Infinite loop Condition never becomes false Update loop variable or add a break guard
Modifying array while iterating Push/pop affects iteration state Iterate a copy or collect changes
Forgot to unset($v) after reference foreach Reference leaks into next operations unset($v) after loop
Slow loops over large data Creating big arrays consumes RAM Use generators or chunked queries

Practice Tasks

  1. Use a for loop to print the first 10 multiples of 7 on one line.
  2. Given an array of prices, use foreach by reference to add 18% GST to each item (then unset($item)).
  3. Write a while loop that reads a file line by line until EOF, counting lines that contain the word “PHP”.
  4. Create a generator rangeStep($start, $end, $step) and iterate it with foreach.
  5. Use nested loops to print a 10×10 multiplication table; break both loops when the product exceeds 60.
Next: Continue with Functions (parameters, returns, default/variadic args, type hints, anonymous functions, closures, and best practices).