Loops
Learn how to repeat code in PHP using for, while, do-while, and foreach loops, including nested loops.
Introduction
Loops let you repeat a block of code without writing it out multiple times — printing a list of products, processing every row from a database, or retrying an operation until it succeeds. PHP provides four loop constructs, each suited to slightly different situations.
In this lesson you will learn for, while, do-while, and foreach, including how foreach can access both keys and values, how to nest loops inside one another, and how the four loop types compare when solving the exact same task.
- How to write for, while, do-while, and foreach loops.
- The one guarantee that makes do-while different from while.
- How to loop over arrays with foreach, including keys and values.
- How to nest loops to work with grids or multi-level data.
- When to reach for each loop type.
The for Loop
A for loop is ideal when you know in advance how many times you want to repeat something. It packs initialization, condition, and increment into one line: for (initialization; condition; increment).
<?php
for ($i = 1; $i <= 5; $i++) {
echo "Count: $i\n";
}Count: 1
Count: 2
Count: 3
Count: 4
Count: 5The loop starts by setting $i to 1, checks the condition ($i <= 5) before every iteration, runs the body if true, then increments $i and checks again — repeating until the condition becomes false.
The while Loop
A while loop repeats its body as long as its condition remains true. It checks the condition before each iteration, so if the condition starts out false, the body never runs at all.
<?php
$i = 1;
while ($i <= 5) {
echo "Count: $i\n";
$i++;
}Count: 1
Count: 2
Count: 3
Count: 4
Count: 5Use while when the number of iterations is not known ahead of time — for example, reading lines from a file until you reach the end, or retrying a connection until it succeeds.
The do-while Loop
A do-while loop is like while, but it checks the condition after the body runs instead of before. That guarantees the body executes at least once, even if the condition is false from the very start.
<?php
$i = 10;
do {
echo "Runs once even though condition is false: $i\n";
$i++;
} while ($i < 5);Runs once even though condition is false: 10Even though $i < 5 is false immediately (10 is not less than 5), the body still runs one time before the condition is checked. This makes do-while useful for things like showing a menu at least once before checking whether the user wants to exit.
The foreach Loop
foreach is built specifically for iterating over arrays (and other iterable structures), so you never have to manage an index counter manually.
<?php
$fruits = ["Apple", "Banana", "Cherry"];
foreach ($fruits as $fruit) {
echo "I like $fruit\n";
}I like Apple
I like Banana
I like CherryWhen you also need the key (the index for a plain array, or the key for an associative array), use the as $key => $value form.
<?php
$prices = [
"Coffee" => 3.50,
"Tea" => 2.75,
"Juice" => 4.00,
];
foreach ($prices as $item => $price) {
echo "$item costs \$$price\n";
}Coffee costs $3.5
Tea costs $2.75
Juice costs $4Nested Loops
A loop can contain another loop inside it — useful for working with grids, tables, or combinations of two lists. The inner loop completes all of its iterations for every single iteration of the outer loop.
<?php
for ($row = 1; $row <= 3; $row++) {
for ($col = 1; $col <= 3; $col++) {
echo "($row,$col) ";
}
echo "\n";
}(1,1) (1,2) (1,3)
(2,1) (2,2) (2,3)
(3,1) (3,2) (3,3)This pattern is common for generating multiplication tables, rendering grid-based layouts, or comparing every item in one list against every item in another.
Comparing All Four Loops
To see how similar these constructs really are, here is the exact same task — printing the numbers 1 through 3 — written with each loop type.
<?php
// for
for ($i = 1; $i <= 3; $i++) {
echo $i . " ";
}1 2 3 <?php
// while
$i = 1;
while ($i <= 3) {
echo $i . " ";
$i++;
}1 2 3 <?php
// do-while
$i = 1;
do {
echo $i . " ";
$i++;
} while ($i <= 3);1 2 3 <?php
// foreach
foreach ([1, 2, 3] as $i) {
echo $i . " ";
}1 2 3 All four produce identical output here, but they fit different situations: for suits a known range, while and do-while suit condition-driven repetition, and foreach is the natural choice whenever you already have an array to walk through.
Common Mistakes
- Forgetting to increment the counter in a while loop, causing an infinite loop.
- Using foreach when you actually need to modify the original array by reference (requires foreach ($arr as &$value)).
- Assuming do-while checks its condition first — it always runs the body at least once.
- Reusing the same loop variable name in nested loops, causing the inner loop to overwrite the outer one.
Best Practices
- Use for when the number of iterations is known in advance.
- Use while or do-while when repetition depends on a condition rather than a count.
- Use foreach whenever you are iterating over an array — it is clearer and less error-prone than manual indexing.
- Give nested loop variables distinct names, like $row and $col, to avoid confusion.
Frequently Asked Questions
What is the main difference between while and do-while?
while checks its condition before running the body, so it may run zero times. do-while checks after, so it always runs the body at least once.
Can foreach modify the original array?
By default no, since it works on a copy of each value. To modify the original array, iterate by reference: foreach ($arr as &$value).
How many levels can loops be nested?
There is no strict limit in PHP, but nesting more than two or three levels usually signals the code could be restructured for clarity.
Is foreach slower than for?
For array iteration, foreach is typically just as fast or faster than a manual for/index loop, and it is generally the more idiomatic choice.
Key Takeaways
- for is best when the number of iterations is known ahead of time.
- while checks its condition before each iteration and may never run.
- do-while always runs its body at least once before checking the condition.
- foreach is purpose-built for arrays, with an as $key => $value form for accessing both.
- Loops can be nested to work with grids or combinations of data.
Summary
Loops are the foundation of repeating work in PHP. You now know all four loop constructs, when each one fits best, how foreach handles keys and values, and how loops can be nested to handle multi-dimensional problems.
- You can write for, while, do-while, and foreach loops.
- You understand the guarantee that makes do-while unique.
- You can iterate over arrays with keys and values using foreach.
- You are ready to learn how to control loops with break, continue, and goto.