devnotes.

Loops: for, while, foreach

// for — when you know how many iterations you need
for ($i = 0; $i < 5; $i++) {
    echo $i;
}

// while — repeats as long as a condition holds
$count = 0;
while ($count < 5) {
    echo $count;
    $count++;
}

// do-while — always runs the body at least once
do {
    echo $count;
    $count--;
} while ($count > 0);

// foreach — the most common loop for arrays
$fruits = ['apple', 'banana', 'cherry'];
foreach ($fruits as $fruit) {
    echo $fruit;
}

$prices = ['apple' => 1.50, 'banana' => 0.75];
foreach ($prices as $name => $price) {
    echo "$name costs $price";
}

Loop control:

  • break exits the loop immediately.
  • continue skips to the next iteration.
  • Both accept an optional numeric argument to break/continue out of nested loops: break 2;.
foreach ($orders as $order) {
    if ($order->isCancelled()) {
        continue; // skip cancelled orders
    }
    if ($order->total > 10000) {
        break; // stop processing once a very large order is found
    }
    process($order);
}

When modifying an array by reference inside foreach, use &$value — but always unset($value) right after the loop to avoid a common bug where the reference lingers and corrupts later code.

PHP Loops: for, while, foreach Tutorial | DevNotes