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
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
$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:
$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:
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:
<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:
$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:
$prices = [10, 20, 30];
foreach ($prices as &$price) {
$price = $price * 1.2;
}
unset($price); // break the reference when you're doneThe 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-whilealways runs once.foreach ($array as $value)visits every item; add$key =>for keys.breakexits a loop;continueskips 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.
A times table
<?php
$n = 8;
for ($i = 1; $i <= 4; $i++) {
echo "$n x $i = " . ($n * $i) . "\n";
}8 x 1 = 8
8 x 2 = 16
8 x 3 = 24
8 x 4 = 32Line-by-line explanation
- Line 3$i takes the values 1 to 4.
- Line 4Variables inside double quotes are replaced by their values; the maths is joined on with a dot.
A menu built with foreach
<?php
$drinks = ["Espresso", "Latte", "Mocha"];
?>
<ul>
<?php foreach ($drinks as $drink): ?>
<li><?= $drink ?></li>
<?php endforeach; ?>
</ul><ul>
<li>Espresso</li>
<li>Latte</li>
<li>Mocha</li>
</ul>Line-by-line explanation
- Line 2An array of three drinks.
- Lines 5 to 7The <li> line is produced once for each drink. The output shows the HTML sent to the browser.
break and continue
<?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";Stopping: limit reached
Total: 44Line-by-line explanation
- Lines 6 to 8Empty orders are skipped.
- Lines 9 to 12Once the total passes 30, the loop stops early.
- 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
$i = 0;
while ($i < 3) {
echo $i;
}$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
foreach ($colour as $colours) { ... }foreach ($colours as $colour) { ... }The array comes first, then as, then the name for each item.
Printing user data without escaping
foreach ($comments as $c) {
echo "<p>$c</p>";
}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.
Complete the loop so it prints each fruit.
$fruits = ["apple", "kiwi"];
($fruits $fruit) {
echo $fruit;
}
What does this print?
for ($i = 0; $i < 6; $i += 2) {
echo $i;
}
What does this print?
$n = 1;
while ($n < 50) {
$n *= 3;
}
echo $n;
Which loop is designed for walking through arrays?
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.
What does
$i++do?- Doubles $i
- Prints $i
- Resets $i
- Adds 1 to $i
In
foreach ($prices as $item => $price), what is$item?- The value
- The array length
- The previous value
- The key
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
Which keyword ends the alternative foreach syntax used in templates?
- end
- }
- endforeach
- done
Which loop is usually best for going through an array?
- while
- foreach
- do-while
- for with a hard-coded number