πŸ“ Web Development

PHP Loops: while, for and foreach Explained

Aug 16, 20265 min read4 viewsBy Flow

PHP loops let you run the same block of code again and again. Copying three lines twenty times is how beginners build their first list. Loops are how everyone else does it.

PHP loops tutorial cover: while, for and foreach explained

The while loop

A while loop keeps going as long as its condition stays true.

<?php
$count = 1;

while ($count <= 5) {
    echo "Count is " . $count . "<br>";
    $count++;
}
?>

Output:

PHP loops output: a while loop printing Count is 1 through Count is 5

Three things must be right here. Miss any one and it breaks.

  • the variable exists before the loop starts
  • the condition can actually become false β€” while it stays true, the loop keeps running. Write while (true) and it never stops.
  • something inside the loop moves the variable towards that β€” the increment

That last line, $count++, is the one people forget. It means "add one to $count". You can write it the long way as $count = $count + 1; β€” inside a loop, $count++ is just shorter. If you have not read the PHP operators lesson yet, go back and read that one first.

Leave the increment out and the condition never changes. The loop never ends. The page just hangs until PHP gives up.

The do while loop

A do while is the same idea with one change. It checks the condition in the while line after running the do block, so the body always runs at least once.

<?php
$number = 10;

do {
    echo "This runs once, even though the condition is false.";
} while ($number < 5);
?>

Output:

PHP do while loop output showing the body runs once even though the condition is false

You will use this far less than while. It fits when the work must happen before you can tell whether to repeat it.

The for loop

When you know how many times to repeat, for puts all three parts β€” the $i variable, the condition, and the increment $i++ β€” on one line. Then there is nothing to forget.

<?php
for ($i = 1; $i <= 5; $i++) {
    echo "Number " . $i . "<br>";
}
?>

Output:

PHP for loop output printing Number 1 through Number 5

Read the brackets as three separate instructions, split by semicolons:

  • $i = 1 runs once, before the loop starts
  • $i <= 5 is checked before every pass
  • $i++ runs after every pass

The variable is usually called $i, short for index. There is no rule about it. But everyone does it, so following the habit makes your code easier to read.

You can count down, or in steps.

<?php
for ($i = 10; $i >= 0; $i -= 2) {
    echo $i . " ";
}
?>

Output:

PHP for loop counting down in steps of two, printing 10 8 6 4 2 0

foreach, the PHP loops workhorse

This is the one you will use most. foreach walks every item in an array. You never touch a counter.

<?php
$languages = ["PHP", "JavaScript", "Python"];

foreach ($languages as $language) {
    echo $language . "<br>";
}
?>

Output:

PHP foreach loop output listing PHP, JavaScript and Python on separate lines

On each pass PHP puts the next item into $languageΒ from theΒ $languagesΒ and runs the block. It stops on its own when the array runs out.

No counter. No condition. Nothing to get wrong.

Need the key as well? Ask for both.

<?php
$prices = ["Coffee" => 250, "Tea" => 150, "Juice" => 300];

foreach ($prices as $item => $price) {
    echo $item . " costs " . $price . " rupees<br>";
}
?>

Output:

PHP foreach with key and value printing Coffee 250, Tea 150 and Juice 300 rupees

Match the two lines up. In $prices, "Coffee" is the key and 250 is the value. In foreach ($prices as $item => $price), $item picks up the key and $price picks up the value, so on the first pass $item is "Coffee" and $price is 250.

The names are yours to choose. PHP fills the variable before the arrow with the key, and the one after it with the value. Calling them $item and $price just makes the line read like what it does.


Arrays are the next lesson, where this shape comes up constantly.

Steering PHP loops with break and continue

Two words let you control a loop from the inside.

break leaves the loop straight away.

<?php
for ($i = 1; $i <= 10; $i++) {
    if ($i === 4) {
        break;
    }
    echo $i . " ";
}
?>

Output:

PHP break statement stopping the loop at 4, printing 1 2 3

continue skips the rest of this pass and starts the next one.

<?php
for ($i = 1; $i <= 6; $i++) {
    if ($i % 2 !== 0) {
        continue;
    }
    echo $i . " ";
}
?>

Output:

PHP continue statement skipping odd numbers, printing 2 4 6

That one prints only the even numbers. It uses the modulus operator from lesson three. Odd numbers hit continue and never reach the echo.

Nested PHP loops

A loop inside a loop runs the inner one fully for every single pass of the outer one.

<?php
for ($row = 1; $row <= 3; $row++) {
    for ($col = 1; $col <= 3; $col++) {
        echo $row . "x" . $col . " ";
    }
    echo "<br>";
}
?>

Output:

Nested PHP loops output printing a three by three grid from 1x1 to 3x3

Notice the cost. Three passes outside and three inside is nine runs, not six. With a hundred each it is ten thousand.

Nested loops are fine and often needed. They are also where slow pages come from. So notice when you write one.

Three mistakes with PHP loops

The infinite loop. Forget to advance the variable and the script runs until the server stops it. If a page hangs while you learn loops, this is almost always why.

Off by one. Starting at zero with $i < 5 runs five times. Starting at one with $i <= 5 also runs five times. Decide which end you want before you write it.

Using for where foreach belongs. Looping an array by index works. But foreach cannot run past the end, cannot miscount, and says plainly what you meant.

Common questions about PHP loops

The questions people search for most when a loop refuses to behave.

Why does my PHP page hang or freeze when I run a loop?

Almost always an infinite loop. The condition never becomes false because nothing inside the loop changes the variable it tests β€” usually a missing $count++. PHP keeps going until the server stops the script.

What is the difference between for and foreach in PHP?

Use for when you know how many times to repeat and you need the counter. Use foreach to walk every item in an array β€” it cannot run past the end and it cannot miscount, so it is the safer choice for arrays.

What is the difference between while and do while?

A while loop checks the condition before running the block, so it may never run at all. A do while checks afterwards, so the block always runs at least once.

How do I stop a PHP loop early?

break leaves the loop immediately. continue skips the rest of the current pass and starts the next one. Both work inside for, while and foreach.

What is next

Those are the PHP loops you will use daily. They matter most when there is a collection to walk through, and that is exactly what arrays are.

Carry on with PHP arrays: lists, keys and functions. The conditions used inside these loops come from PHP if else.

Comments

Loading comments...

Link copied to clipboard