Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 147 ยท Control Flow

while, do-while and for Loops

Learn PHP while, do-while and for loops - counters, reading input until it ends, nested loops, infinite-loop and off-by-one bugs, float counters and the alternative syntax.

Computers are good at doing the same thing many times without getting bored. A loop repeats a block of code: print every row of a report, retry a calculation until it's precise enough, read lines of input until there are none left. Without loops you'd copy and paste the same code over and over, and you still couldn't handle data whose size you don't know in advance.

PHP has four loops. This lesson covers the three that repeat based on a condition: while, do-while and for. The fourth, foreach, walks through arrays and gets its own lesson next, in foreach Loops, because it's the one you'll use most for collections. You'll also learn the bugs that loops invite (infinite loops, off-by-one errors, floating-point counters) and the template-friendly alternative syntax.

The while loop

A while loop checks a condition, and if it's true, runs the block. Then it checks the condition again, and again, until the condition is false:

PHP
while (condition) {
    // repeated while the condition is true
}

Each pass through the block is called an iteration. Because the condition is checked before each iteration, a while loop whose condition is false at the start never runs its block at all.

PHP Counting with while

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Three things make a counting loop work: the counter starts with a value ($count = 1), the condition tests it ($count <= 5), and the block changes it ($count++). Forget the last part and the condition never becomes false.

After the loop, $count is 6, the first value that failed the test. PHP variables aren't limited to the block they're created in, so loop variables are still around after the loop ends.

The second loop shows where while really shines: when you don't know in advance how many iterations you need. You only know when to stop.

Reading input until it runs out

A very common while pattern reads input line by line. fgets(STDIN) returns the next line, or false when there are no more lines, so you can loop until it returns false:

PHP Summing every input line

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The condition ($line = fgets(STDIN)) !== false does two jobs: it assigns the next line to $line, and it compares the result with false. The parentheses around the assignment are essential, because !== binds more tightly than =. The strict !== matters too: a line containing just 0 would be falsy, but it isn't false, so the loop keeps going. Add or remove lines in the Input box and run it again.

The do-while loop

A do-while loop checks its condition after each iteration, so the block always runs at least once:

PHP
do {
    // runs once, then again while the condition is true
} while (condition);

Note the semicolon after the condition; it's required. This loop fits situations where you must do something before you can decide whether to repeat it, like asking for input and then checking whether it was valid:

PHP Asking until the answer is valid

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The preset input contains two bad answers before a good one, so you see the loop repeat. ctype_digit() checks that the text contains only digits, which rejects twelve; the range check rejects 0. The exit(1) stops the script if the input runs out, so a missing line can't cause an endless loop. You'll learn more about exit codes in Command-Line PHP.

In practice, do-while is the least used of the loops. Many developers prefer while (true) with a break for this kind of input loop, as shown in break, continue and Loop Control. Use whichever reads more clearly.

The for loop

Counting loops are so common that they have their own compact form. A for loop puts the three parts of a counter (start, test, change) on one line:

PHP
for (initialization; condition; update) {
    // repeated while the condition is true
}
  1. The initialization runs once, before anything else.
  2. The condition is checked before every iteration; the loop ends when it's false.
  3. The update runs after every iteration, before the next check.
PHP Counting up, down and in steps

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Everything about the counter lives in the loop header, so you can see at a glance how many times the loop runs. That's why for is the usual choice when you know the number of iterations, and while when you only know the stopping condition. Any for loop can be rewritten as a while loop and vice versa; pick the one that reads best.

The last loop shows that each part can contain several expressions separated by commas. Here two counters move toward each other until they meet.

Looping over an indexed array with for

You can use a counter to visit every element of a list by its index. Arrays start at index 0, so the last index is count($array) - 1:

PHP Indexes with a for loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The first loop calls count() once in the initialization instead of in the condition. With $i < count($planets) in the condition (as in the second loop), PHP recounts on every iteration. For a small array that's harmless and count() is fast, but storing the size is a tidy habit.

Tip: For simply visiting every element of an array, foreach ($planets as $planet) is shorter, works with any keys, and can't go out of bounds. Use a for loop when you need the index arithmetic itself, such as every second element or comparing neighbors. See foreach Loops.

Nested loops

A loop can contain another loop. The inner loop runs completely for every single iteration of the outer one, so the total work is the product of both counts:

PHP A multiplication table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The outer loop picks a row; the inner loop fills in its columns. Give nested counters meaningful names like $row and $col. With $i and $j it's easy to increment the wrong one, and the bug can be surprisingly hard to spot. Nesting multiplies the work: two loops of 1,000 iterations each run the inner block a million times. That's fine occasionally, but watch for it with large data.

Loop bugs to avoid

Infinite loops

If the condition never becomes false, the loop runs forever. The usual causes are forgetting to update the counter, updating the wrong variable, or moving in the wrong direction:

PHP
$i = 0;
while ($i < 10) {
    echo $i;
    // forgot $i++: prints 0 forever
}

for ($i = 10; $i > 0; $i++) {   // counts UP while testing for > 0
    echo $i;
}

On a web server, PHP's max_execution_time setting (30 seconds by default) eventually stops a runaway script. On the command line there's no time limit by default, so press Ctrl + C to stop it; our editor stops programs after a few seconds. An intentional infinite loop, while (true) or for (;;), is fine as long as something inside it breaks out.

Off-by-one errors

The most common loop bug runs one iteration too many or too few. Ask two questions about every counting loop: what is the first value, and what is the last? $i <= 10 includes 10; $i < 10 stops at 9. With array indexes, $i <= count($array) reads one element past the end and produces an Undefined array key warning.

Floating-point counters

Decimal fractions like 0.1 can't be stored exactly in binary (see Integers and Floats), so a counter that adds 0.1 repeatedly drifts, and an exact != test can miss its target. This example has a safety limit, so it stops instead of running forever:

PHP Why floats make poor loop counters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

After ten additions, $x is 0.99999999999999989, not 1.0, so $x != 1.0 stays true and the loop sails past, stopping only because of the 20-step limit. Count with integers and derive the decimal value from the counter, as the second loop does, or at least use < and > instead of == and != with floats.

Alternative syntax

Like if, the loops have a colon-based syntax for templates: while (...): ... endwhile; and for (...): ... endfor; (and foreach ... endforeach;). It's meant for files that are mostly HTML:

PHP A for loop inside a template

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output is HTML source shown as text; in a browser the spans would render as five stars, three of them highlighted by CSS. There's no alternative syntax for do-while. In normal PHP code, keep using braces. More template techniques are in PHP and HTML Templates.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How many times does the body run? $n = 10; while ($n < 5) { $n++; }

    A while loop checks its condition first. 10 < 5 is false, so the body never runs.
  2. 2. What does $i = 5; do { echo $i; $i++; } while ($i < 5); print?

    do-while runs the body once before checking the condition, so it prints 5. Then 6 < 5 is false and the loop ends.
  3. 3. What does for ($i = 0; $i < 3; $i++) { echo $i; } echo $i; print?

    The loop prints 0, 1 and 2. It ends when $i becomes 3, and the variable still exists after the loop, so the last echo prints 3.
  4. 4. Why is while (($line = fgets(STDIN)) !== false) written with !==?

    fgets() returns false at the end of the input. A loose or truthy check would also stop on a line that is falsy, such as "0" (without a line break, at the very end).
  5. 5. Which loop condition reads past the end of an array with count($items) elements, starting at $i = 0?

    The last valid index is count($items) - 1. <= count($items) runs one extra iteration with an index that doesn't exist: a classic off-by-one error.

Summary

  • while (cond) { ... } checks the condition before each iteration and may run zero times; it's ideal when you only know when to stop.
  • do { ... } while (cond); checks after each iteration, so the body runs at least once; don't forget the final semicolon.
  • for (init; cond; update) { ... } keeps a counter's start, test and change in one line; each part can hold comma-separated expressions.
  • Read input until it ends with while (($line = fgets(STDIN)) !== false).
  • Nested loops multiply the work; give their counters meaningful names.
  • Avoid infinite loops (update the counter), off-by-one errors (check the first and last values) and float counters (count with integers).
  • Templates can use while: ... endwhile; and for: ... endfor;.

Next: foreach Loops