PHP has four loop types. foreach is what you'll use for arrays constantly; the other three cover everything else.
Best when you know exactly how many times to repeat, or need a counter:
<?php
for ($i = 1; $i <= 5; $i++) {
echo "Count: $i\n";
}
?>Repeats as long as a condition stays true — used when you don't know the number of iterations ahead of time:
<?php
$count = 0;
while ($count < 3) {
echo "Iteration $count\n";
$count++;
}
?>Identical to while, except the condition is checked after the loop body runs — guaranteeing at least one run, even if the condition starts false:
<?php
$count = 10;
do {
echo "This runs once, even though $count is not < 3.\n";
} while ($count < 3);
?>Purpose-built for arrays — you already used this in the Indexed Arrays and Associative Arrays lessons:
<?php
$fruits = ["apple", "banana", "mango"];
foreach ($fruits as $index => $fruit) {
echo "$index: $fruit\n";
}
?><?php
for ($i = 1; $i <= 10; $i++) {
if ($i === 6) break; // stops the loop entirely
if ($i % 2 === 0) continue; // skips this iteration, keeps looping
echo $i . " ";
}
// Output: 1 3 5
?>foreach for arrays, almost always
Reaching for for or while to loop over an array — using a manual counter and $fruits[$i] — works, but foreach is almost always clearer and less error-prone for that specific job. Save for/while for cases that aren't really "go through this list."