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
for ($i = 5; $i >= 1; $i--) {
echo $i . "... ";
}
echo "Liftoff!";
?>
5... 4... 3... 2... 1... Liftoff!
while: condition-driven loops
<?php
$stock = 100;
$day = 0;
while ($stock > 0) {
$stock -= 30;
$day++;
}
echo "Stock ran out after day $day";
?>
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 $fruits = ["apple", "banana", "cherry"]; foreach ($fruits as $fruit) { echo strtoupper($fruit) . "\n"; } ?>
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
$numbers = [4, 7, -1, 12, 9];
foreach ($numbers as $n) {
if ($n === -1) {
break;
}
if ($n % 2 !== 0) {
continue;
}
echo "Even: $n\n";
}
?>
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.
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.