PHP Loops
Loops let PHP run the same block of code over and over until a condition tells it to stop, saving you from writing repetitive statements by hand.
Why loops matter
Almost every real program needs to repeat work: printing each row of a report, sending an email to every subscriber, or adding up a column of numbers. Without loops you would have to copy and paste the same lines dozens or thousands of times, and you would never know the exact count ahead of time. A loop expresses the idea 'keep doing this while it still makes sense' in just a few lines.
PHP gives you four loop constructs. They all repeat code, but each one is shaped for a slightly different situation, and learning when to reach for which is the real skill.
The anatomy of a loop
- Initialization: setting up a starting value, such as a counter at zero.
- Condition: a test checked before (or after) each pass that decides whether to keep going.
- Body: the statements that actually do the work on each pass.
- Update: changing something each time so the loop eventually ends, like adding one to the counter.
A first loop with while
<?php
$count = 1;
while ($count <= 3) {
echo "Pass number $count\n";
$count++;
}
?>The same idea with for
<?php
for ($count = 1; $count <= 3; $count++) {
echo "Pass number $count\n";
}
?>You can also steer a loop from inside its body: the break statement stops the loop entirely, while continue skips the rest of the current pass and jumps straight to the next one. Both work in all four loop types and are covered in the pages that follow.
Exercise: PHP Loops
What is the key difference between while and do-while loops in PHP?