PHP Loops

Repeat code with for, while and foreach loops, and use loops to build HTML lists and tables.

Lesson 5 of 86Beginner18 min read

A lot of what PHP does on a website is repetition: print every product in a category, every comment under a post, every row of an order table. Loops let you write that code once and have PHP repeat it for each item.

PHP has the familiar for and while loops, plus foreach, which is designed for walking through arrays and is the loop you'll use most in real PHP code.

In this lesson you'll use all three, control loops with break and continue, and use a loop to generate HTML, which is exactly how dynamic pages are built.

The for loop

PHP
for ($i = 1; $i <= 5; $i++) {
    echo "Row $i<br>";
}

The three parts are the start ($i = 1), the condition checked before each pass ($i <= 5) and the update after each pass ($i++). Use a for loop when you know how many times to repeat.

while and do-while

PHP
$tickets = 3;
while ($tickets > 0) {
    echo "Selling ticket $tickets\n";
    $tickets--;
}

while checks its condition before each pass. do { ... } while (condition); checks after, so it always runs at least once. As with any while loop, make sure something inside it eventually makes the condition false.

foreach

foreach visits every item of an array, one at a time:

PHP
$colours = ["red", "green", "blue"];
foreach ($colours as $colour) {
    echo "<li>$colour</li>";
}

To get the key (position or name) as well as the value, use as $key => $value:

PHP
foreach ($colours as $i => $colour) {
    echo "$i: $colour\n";
}

You'll learn much more about arrays and their keys in the next lesson.

Generating HTML with loops

A common pattern is to open an HTML element, loop to create its children, then close it:

PHP
<ul>
<?php foreach ($menu as $item): ?>
  <li><?= $item ?></li>
<?php endforeach; ?>
</ul>

This alternative syntax, with a colon and endforeach, is popular in templates because it keeps HTML readable. There are matching endfor, endwhile and endif keywords.

Nested loops

You can put one loop inside another. The inner loop runs all the way through for every single pass of the outer loop, which is how you build anything with rows and columns, such as a seating plan or a table:

PHP
$rows = ["A", "B"];
for ($r = 0; $r < count($rows); $r++) {
    for ($seat = 1; $seat <= 3; $seat++) {
        echo $rows[$r] . $seat . " ";
    }
    echo "\n";
}

This prints A1 A2 A3 on the first line and B1 B2 B3 on the second. Give each loop its own variable name ($r and $seat here). Reusing $i in both loops is a classic bug, because the inner loop changes the counter the outer loop depends on.

Changing array items inside foreach

By default, foreach hands you a copy of each value, so changing it inside the loop doesn't touch the array. Put & in front of the variable to work on the real item instead:

PHP
$prices = [10, 20, 30];
foreach ($prices as &$price) {
    $price = $price * 1.2;
}
unset($price); // break the reference when you're done

The unset() line matters. After the loop, $price still points at the last item, and a later loop that reuses the name would overwrite it by accident.

Which loop should you use?

  • Use foreach whenever you're walking through an array. It's the shortest and hardest to get wrong, since there's no counter to manage.
  • Use for when you need a counter, such as printing numbers 1 to 10 or stepping through every second item.
  • Use while when you don't know in advance how many passes you need, for example reading lines from a file until there are none left.
  • Use do-while for the rare case where the body must run once before the check, such as showing a menu before asking whether to show it again.

PHP Loops Syntax

Loop syntax

for ($i = 0; $i < 10; $i++) { }

while ($condition) { }

do { } while ($condition);

foreach ($items as $item) { }
foreach ($items as $key => $value) { }

PHP Loops Summary

  • for ($i = 0; $i < $n; $i++) repeats a set number of times.
  • while (condition) repeats while true; do-while always runs once.
  • foreach ($array as $value) visits every item; add $key => for keys.
  • break exits a loop; continue skips to the next pass.
  • Loops generate repeated HTML; escape user data with htmlspecialchars().

PHP Loops Examples

Each example shows the code, the output it produces and what each part does.

Example 1

A times table

PHP
<?php
$n = 8;
for ($i = 1; $i <= 4; $i++) {
    echo "$n x $i = " . ($n * $i) . "\n";
}
Output
8 x 1 = 8
8 x 2 = 16
8 x 3 = 24
8 x 4 = 32
Line-by-line explanation
  1. Line 3$i takes the values 1 to 4.
  2. Line 4Variables inside double quotes are replaced by their values; the maths is joined on with a dot.
Example 2

A menu built with foreach

PHP
<?php
$drinks = ["Espresso", "Latte", "Mocha"];
?>
<ul>
<?php foreach ($drinks as $drink): ?>
  <li><?= $drink ?></li>
<?php endforeach; ?>
</ul>
Output
<ul>
  <li>Espresso</li>
  <li>Latte</li>
  <li>Mocha</li>
</ul>
Line-by-line explanation
  1. Line 2An array of three drinks.
  2. Lines 5 to 7The <li> line is produced once for each drink. The output shows the HTML sent to the browser.
Example 3

break and continue

PHP
<?php
$orders = [12, 0, 7, 0, 25, 3];
$total = 0;

foreach ($orders as $qty) {
    if ($qty === 0) {
        continue;
    }
    if ($total > 30) {
        echo "Stopping: limit reached\n";
        break;
    }
    $total += $qty;
}
echo "Total: $total";
Output
Stopping: limit reached
Total: 44
Line-by-line explanation
  1. Lines 6 to 8Empty orders are skipped.
  2. Lines 9 to 12Once the total passes 30, the loop stops early.
  3. Line 13The total grows 12, 19, then 44. The next order (3) finds it above 30, so the loop stops.

Common PHP Loops Mistakes

Forgetting to update a while loop

Don't
$i = 0;
while ($i < 3) {
    echo $i;
}
Do
$i = 0;
while ($i < 3) {
    echo $i;
    $i++;
}

The first version prints 0 forever, until PHP's time limit stops it.

foreach in the wrong order

Don't
foreach ($colour as $colours) { ... }
Do
foreach ($colours as $colour) { ... }

The array comes first, then as, then the name for each item.

Printing user data without escaping

Don't
foreach ($comments as $c) {
    echo "<p>$c</p>";
}
Do
foreach ($comments as $c) {
    echo "<p>" . htmlspecialchars($c) . "</p>";
}

PHP Loops in Real Projects

Loops on real sites

A blog's home page loops through the latest posts, an online shop loops through the products in a category, and an admin panel loops through database rows to build a table. In WordPress themes, this is literally called "The Loop".

PHP Loops FAQ

How do I loop through an associative array in PHP?

Use foreach with both the key and the value: foreach ($prices as $item => $price) { echo "$item costs $price"; }. If you only need the keys, loop over array_keys($prices); for just the values, leave out the $item => part.

How do I break out of nested loops in PHP?

break accepts a number of levels: break 2; leaves the inner loop and the loop around it. continue 2; likewise skips to the next pass of the outer loop. For more than two levels, moving the loops into a function and using return is clearer.

How do I loop over a range of numbers?

Use a for loop, or foreach (range(1, 10) as $n). range() also accepts a step, range(0, 100, 10), and letters, range('a', 'e'). For very large ranges, a for loop avoids building the whole array in memory first.

How do I loop over the characters of a string?

Split it into an array first: foreach (mb_str_split($word) as $char). mb_str_split keeps accented letters and emoji whole; str_split works byte by byte, which is fine only for plain ASCII text.

Should I call count() in a for loop condition?

for ($i = 0; $i < count($items); $i++) calls count on every pass. It's fast for arrays, but storing the count first, $n = count($items);, is a common habit and avoids surprises if the array changes during the loop. foreach avoids the question altogether.

PHP Loops Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Fill in the blankseasy

Complete the loop so it prints each fruit.

$fruits = ["apple", "kiwi"];
 ($fruits  $fruit) {
    echo $fruit;
}
Predict the outputeasy

What does this print?

for ($i = 0; $i < 6; $i += 2) {
    echo $i;
}
Predict the outputmedium

What does this print?

$n = 1;
while ($n < 50) {
    $n *= 3;
}
echo $n;
Multiple choicemedium

Which loop is designed for walking through arrays?

Predict the outputmedium

What does this print?

$prices = ["tea" => 2, "cake" => 3];
foreach ($prices as $item => $price) {
    echo "$item:$price ";
}

PHP Loops Quiz

5 questions to check what you learned.

  1. What does $i++ do?

    • Doubles $i
    • Prints $i
    • Resets $i
    • Adds 1 to $i
  2. In foreach ($prices as $item => $price), what is $item?

    • The value
    • The array length
    • The previous value
    • The key
  3. Why use htmlspecialchars() when printing user data?

    • To stop users' text from being run as HTML or JavaScript
    • To make text bold
    • To translate text
    • To speed up the loop
  4. Which keyword ends the alternative foreach syntax used in templates?

    • end
    • }
    • endforeach
    • done
  5. Which loop is usually best for going through an array?

    • while
    • foreach
    • do-while
    • for with a hard-coded number