Loops

PHP has the standard for and while loops, but the one you'll reach for constantly once arrays enter the picture is foreach — it's purpose-built for walking through a collection without managing an index by hand.

for: counting loops

PHP countdown.php
<?php
for ($i = 5; $i >= 1; $i--) {
    echo $i . "... ";
}
echo "Liftoff!";
?>
Output
5... 4... 3... 2... 1... Liftoff!

while: condition-driven loops

PHP stock.php
<?php
$stock = 100;
$day = 0;

while ($stock > 0) {
    $stock -= 30;
    $day++;
}

echo "Stock ran out after day $day";
?>
Output
Stock ran out after day 4

foreach: walking an array

foreach takes an array and hands you each value in turn, with no index variable to manage — this is the loop you'll use for the vast majority of array work in PHP:

PHP foreach.php
<?php
$fruits = ["apple", "banana", "cherry"];

foreach ($fruits as $fruit) {
    echo strtoupper($fruit) . "\n";
}
?>
Output
APPLE
BANANA
CHERRY

foreach ($fruits as $fruit) reads naturally as "for each item in $fruits, call it $fruit." The Arrays lesson right after this one, and Associative Arrays after that, both lean on foreach heavily.

break and continue

Both work the same as in most C-family languages: break exits the loop immediately, continue skips straight to the next iteration:

PHP break-continue.php
<?php
$numbers = [4, 7, -1, 12, 9];

foreach ($numbers as $n) {
    if ($n === -1) {
        break;
    }
    if ($n % 2 !== 0) {
        continue;
    }
    echo "Even: $n\n";
}
?>
Output
Even: 4
Even: 12

7 is odd, so continue skips it without printing. -1 is the sentinel value that ends the loop entirely with break, so 12 and 9 after it are never reached — even though 12 would otherwise have qualified.

Note: foreach can also destructure key/value pairs directly — foreach ($array as $key => $value) — which becomes essential once you're working with associative arrays instead of plain indexed lists. That's the very next lesson but one.