Loops
| The for loop | |
| Foreach over arrays | |
| while and do-while | |
| break and continue |
The for loop
The for loop bundles three parts in its header: an initialization, a condition checked before every pass, and a step that runs after every pass. It fits counting over a known range, where the start, the end, and the step are all visible in one line.
for ($i = 0; $i < 5; $i++) { echo $i; }
Foreach over arrays
The foreach loop walks an array without a manual index, so there is no counter to misplace and no end to overshoot. Add $key => $value when the index or the key matters, not just the element.
$tags = ["php", "html", "css"]; foreach ($tags as $index => $tag) { echo $index . ": " . $tag; }
while and do-while
The while loop checks its condition first, so the body may run zero times. The do-while loop checks last, so the body always runs at least once. Both need the condition to change inside the body, or the loop never ends.
$left = 3; while ($left > 0) { echo $left; $left--; } do { $left++; } while ($left < 3);
break and continue
The break statement exits the loop at once, while continue skips the rest of the current pass and jumps to the next one. Together they express search, skip, and stop rules without extra flag variables.
foreach ($tags as $tag) { if ($tag === "html") { continue; } if ($tag === "css") { break; } echo $tag; }
Next: Arrays
Article author: Arthur Isaev