Computers are good at doing the same job many times without getting bored. A loop repeats a block of code until a condition says stop. In web pages you use PHP loops to print a list of products, the rows of a table or the options of a dropdown. This lesson builds on PHP Conditions, because every loop is controlled by a condition.
The for loop
Use for when you know in advance how many times to repeat. Its brackets hold three parts separated by semicolons:
- Start: runs once before the loop, usually setting a counter such as
$i = 1. - Condition: checked before every round; the loop continues while it is
true. - Step: runs after every round, usually
$i++.
<?php
$number = 7;
for ($i = 1; $i <= 5; $i++) {
echo "$number x $i = ", $number * $i, "\n";
}7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35
while and do-while
A while loop checks its condition first and repeats as long as it stays true. Use it when you do not know how many rounds you will need, for example “keep adding a monthly deposit until the savings reach a target”. A do-while loop checks the condition at the end, so its body always runs at least once.
<?php
$savings = 5000;
$goal = 20000;
$month = 0;
while ($savings < $goal) {
$savings += 2500;
$month++;
}
echo "Goal reached after $month months with Rs. $savings\n";
$attempt = 10;
do {
echo "This runs once even though $attempt > 3\n";
$attempt++;
} while ($attempt <= 3);Goal reached after 6 months with Rs. 20000 This runs once even though 10 > 3
Watch out: Make sure something inside a while loop eventually makes the condition false. If you forget $savings += 2500;, the loop never ends. On a web server, PHP stops such a script after the max_execution_time limit (30 seconds by default), and the visitor sees an error.
The foreach loop
foreach is the loop you will use most in PHP. It walks through every element of an array without any counter to manage. There are two forms:
foreach ($items as $item)gives you each value in turn.foreach ($items as $key => $value)gives you both the key and the value, which is useful for named data such as prices by product.
<?php
$cities = ["Chennai", "Madurai", "Puducherry"];
foreach ($cities as $city) {
echo "Delivering to $city\n";
}
$menu = ["Filter coffee" => 40, "Masala dosa" => 90, "Idli (2)" => 50];
$total = 0;
foreach ($menu as $dish => $price) {
echo str_pad($dish, 15), "Rs. $price\n";
$total += $price;
}
echo "Total: Rs. $total";Delivering to Chennai Delivering to Madurai Delivering to Puducherry Filter coffee Rs. 40 Masala dosa Rs. 90 Idli (2) Rs. 50 Total: Rs. 180
Notice how the loop also builds a running total. Combining a loop with an accumulator variable is one of the most common patterns in programming.
Changing values while looping
Inside foreach, $price is a copy of each value. Changing it does not change the original array. If you really need to edit the array in place, you can loop by reference with foreach ($menu as &$price), but you must call unset($price); after the loop, otherwise a later loop that reuses $price can silently overwrite the last element. A safer beginner approach is to build a new array inside the loop, or to use array_map(), which you will meet in PHP Arrays.
Nested loops
A loop can sit inside another loop. The inner loop runs completely for every single round of the outer loop. Nested PHP loops are how you would print a seating chart with rows and seats, or a timetable with days and periods. Be careful with size: an outer loop of 1,000 rounds with an inner loop of 1,000 rounds runs the inner body a million times. Use different counter names, such as $row and $seat, so the code stays readable.
break and continue
Two keywords change the normal flow of a loop:
breakleaves the loop immediately, for example once you have found what you were searching for.continueskips the rest of the current round and jumps to the next one, for example to ignore invalid entries.
<?php
$orders = [1200, 0, 450, -30, 800, 15000, 300];
foreach ($orders as $amount) {
if ($amount <= 0) {
continue; // ignore empty or invalid orders
}
if ($amount > 10000) {
echo "Large order found: $amount. Stopping for review.\n";
break; // stop the whole loop
}
echo "Processing order of Rs. $amount\n";
}Processing order of Rs. 1200 Processing order of Rs. 450 Processing order of Rs. 800 Large order found: 15000. Stopping for review.
The order of 300 at the end is never processed, because break ended the loop when it met the large order.
PHP loops in HTML templates
To build a list or table, place the loop around the HTML you want to repeat. The alternative syntax foreach (...): … endforeach; keeps templates tidy:
<ul><?php foreach ($cities as $city): ?><li><?= htmlspecialchars($city) ?></li><?php endforeach; ?></ul>
Wrapping the value in htmlspecialchars() is a good habit whenever data might come from users or a database. You will see why in PHP Forms, and in PHP with MySQL you will use exactly this loop to print rows fetched from a database.
Which loop should I use?
| Situation | Loop |
|---|---|
| Go through every item of an array | foreach |
| Repeat a known number of times | for |
| Repeat until something changes, number of rounds unknown | while |
| Same as while, but the body must run at least once | do-while |
Tip: If you find yourself writing for ($i = 0; $i < count($items); $i++) just to read each item, switch to foreach. It is shorter and avoids off-by-one mistakes.
