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.

LoopRepeatsBest used when
whileAs long as a condition stays trueYou do not know how many passes are needed in advance
do...whileAt least once, then while the condition holdsThe body must always run one time before the test
forA fixed number of times with a counterYou know or can compute the number of iterations
foreachOnce per elementYou want to walk through every item in an array

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";
}
?>
Note: Every loop must have a way to end. If the condition never becomes false and you never break out, you create an infinite loop that hangs the script. Always make sure the update step moves the loop toward its stopping point.

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?