Loops repeat work. foreach is the workhorse for arrays; while and for suit counters and conditions.
foreach
foreach ($items as $item) {
echo $item . "\n";
}
foreach ($user as $key => $value) {
echo "$key: $value\n";
}
for and while
for ($i = 0; $i < 3; $i++) {
echo $i . "\n";
}
$n = 3;
while ($n > 0) {
echo $n-- . "\n";
}
break and continue
break exits the loop; continue skips to the next iteration. Label breaks exist but use sparingly.
Important interview questions and answers
- Q: foreach by value vs reference?
A:foreach ($arr as &$v)modifies the original array—unset$vafter to avoid accidental aliasing. - Q: When avoid foreach?
A: When you need index arithmetic without keys—forcan be clearer; for generators, foreach is ideal.
Self-check
- Which loop is idiomatic for a plain indexed array of strings?
- What does
continuedo inside a loop?
Challenge
Sum with a loop
- Create an array of five integers.
- Use
foreachto compute the sum. - Echo the total.
Done when: the terminal prints the correct sum.