Learn/PHP/5. Loops
Lesson 5 of 15
Sign in

PHP, lesson 5

Loops

A loop runs the same block of code many times. PHP has four kinds, and each fits a different situation.

for: counting

for has three parts in its parentheses: a start, a condition checked before every pass, and an update run after every pass.

If the condition is false from the start, the body never runs. Looping zero times is not an error.

while: until something changes

while checks its condition before every pass. Use it when you don't know in advance how many passes you need:

Something in the body must eventually make the condition false, or the loop never ends.

Reading input until it runs out

fgets() returns false when there's nothing left to read. Assigning inside the condition gives a compact "read every line" loop:

Compare with !== false, not just truthiness. A line containing only 0 is a string that counts as false, and a loose check would stop the loop early.

2 exercises to try what you just read.

Exercise 1

Times table

Press Ctrl Enter or Check to test your code.

Exercise 2

Guess the number

Press Ctrl Enter or Check to test your code.

do-while: at least once

do { ... } while (condition); runs the body first and checks afterwards, so the body always runs at least once. It's the right fit for "ask, then repeat if needed".

foreach: walking through arrays

foreach visits every element of an array. You'll use it constantly from lesson 7 on:

break and continue

  • break leaves the loop immediately.
  • continue skips the rest of this pass and starts the next one.

Both accept a number for nested loops: break 2; leaves the inner and the outer loop.

Accumulators

Most loops build up a result: a total, a count, the biggest value seen so far. Create the variable before the loop, update it inside, and use it after:

Further reading

  • for
  • while and do-while
  • foreach
  • break and continue

Read a whole number n and print its times table from 1 to 10, one line each, in the form n x i = result.

Sample input:

Sample output (first three of ten lines):

The first line is the secret number. Each following line is a guess. For every guess print too low, too high or, when it matches, correct after N guesses and stop reading (ignore any later lines). If the input ends without a correct guess, print not guessed.

Sample input:

Sample output:

<?php

for ($i = 1; $i <= 5; $i++) {
    echo $i, "\n";        // 1 2 3 4 5
}

for ($i = 10; $i > 0; $i -= 2) {
    echo $i, " ";         // 10 8 6 4 2
}
<?php

$balance = 100;
$years = 0;
while ($balance < 200) {
    $balance *= 1.07;
    $years++;
}
echo $years, "\n";
<?php

while (($line = fgets(STDIN)) !== false) {
    $line = trim($line);
    echo "Got: $line\n";
}
<?php

foreach (["apple", "pear", "plum"] as $fruit) {
    echo "I like $fruit\n";
}
<?php

while (($line = fgets(STDIN)) !== false) {
    $line = trim($line);
    if ($line === "") {
        continue;       // ignore blank lines
    }
    if ($line === "quit") {
        break;          // stop reading
    }
    echo "You said $line\n";
}
<?php

$total = 0;
for ($n = 1; $n <= 100; $n++) {
    $total += $n;
}
echo $total, "\n";   // 5050
7
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
42
50
30
42
10
too high
too low
correct after 3 guesses