Loops are used to run the same block of code again and again.
Instead of writing repeated code manually, you can put it inside a loop and let PHP run it based on a condition.
PHP supports four common loop statements: while, do while, for, and foreach. You can also control loop execution with break and continue.
Quick Answer
Use while when you do not know the exact number of iterations. Use do while when the code must run at least once. Use for when you know how many times to repeat. Use foreach when looping through arrays.
- while: repeats while a condition is true.
- do while: runs once first, then checks the condition.
- for: repeats using initialization, condition, and increment in one line.
- foreach: loops through array values or key-value pairs.
- break: exits the loop early.
- continue: skips the current iteration and moves to the next one.
PHP while Loop
The while loop runs as long as the condition is true.
It is useful when the number of iterations is not fixed in advance.
Syntax
while (condition) {
// code
}
Example
<?php
$count = 1;
while ($count <= 5) {
echo $count . "<br>";
$count++;
}
?>
Output
1
2
3
4
5
The loop stops when the condition becomes false.
Common Mistake
If the condition never becomes false, the loop runs forever.
Wrong:
<?php
$count = 1;
while ($count <= 5) {
echo $count;
}
?>
In this example, $count is never incremented.
PHP do while Loop
The do while loop always runs at least once.
The condition is checked after executing the loop body.
Syntax
do {
// code
} while (condition);
Example
<?php
$count = 1;
do {
echo $count . "<br>";
$count++;
} while ($count <= 5);
?>
Output
1
2
3
4
5
The main difference from while is that the loop body executes first.
PHP for Loop
The for loop is commonly used when the number of iterations is already known.
It combines initialization, condition checking, and increment in a single statement.
Syntax
for (initialization; condition; increment) {
// code
}
Example
<?php
for ($count = 1; $count <= 5; $count++) {
echo $count . "<br>";
}
?>
Output
1
2
3
4
5
The for loop is widely used for counters, pagination logic, and indexed array access.
PHP foreach Loop
The foreach loop is specially designed for arrays.
It automatically loops through each element without manually managing indexes.
Loop Through Array Values
<?php
$colors = ["Red", "Green", "Blue"];
foreach ($colors as $color) {
echo $color . "<br>";
}
?>
Output
Red
Green
Blue
Loop Through Associative Arrays
<?php
$user = [
"name" => "John",
"role" => "Admin"
];
foreach ($user as $key => $value) {
echo $key . ": " . $value . "<br>";
}
?>
Output
name: John
role: Admin
If you are working with arrays, you may also like this guide on PHP arrays.
Using break in PHP Loops
The break statement stops the loop immediately.
It is useful when you want to exit the loop early after finding a result.
Example
<?php
for ($count = 1; $count <= 10; $count++) {
if ($count == 5) {
break;
}
echo $count . "<br>";
}
?>
Output
1
2
3
4
When the value becomes 5, the loop exits completely.
Using continue in PHP Loops
The continue statement skips the current iteration and moves to the next one.
Example
<?php
for ($count = 1; $count <= 5; $count++) {
if ($count == 3) {
continue;
}
echo $count . "<br>";
}
?>
Output
1
2
4
5
In this example, the value 3 is skipped.
Nested Loops in PHP
A nested loop means one loop inside another loop.
Nested loops are commonly used for tables, grids, and matrix-style data.
Example
<?php
for ($row = 1; $row <= 3; $row++) {
for ($col = 1; $col <= 2; $col++) {
echo "Row " . $row . " Col " . $col . "<br>";
}
}
?>
Output
Row 1 Col 1
Row 1 Col 2
Row 2 Col 1
Row 2 Col 2
Row 3 Col 1
Row 3 Col 2
Be careful with deeply nested loops because they can affect performance when processing large datasets.
Real-World Examples of PHP Loops
Loops are heavily used in real PHP applications.
Displaying Database Records
Loops are commonly used to display rows returned from a database query.
<?php
$users = [
"John",
"David",
"Maria"
];
foreach ($users as $user) {
echo $user . "<br>";
}
?>
Generating HTML Lists
<?php
$products = ["Laptop", "Mouse", "Keyboard"];
?>
<ul>
<?php foreach ($products as $product) { ?>
<li><?php echo $product; ?></li>
<?php } ?>
</ul>
Creating Table Rows
<table border="1">
<?php for ($row = 1; $row <= 3; $row++) { ?>
<tr>
<td>Row <?php echo $row; ?></td>
</tr>
<?php } ?>
</table>
Loops are also useful in pagination, CSV export, report generation, and API response processing.
Performance Tips for PHP Loops
Loops are simple, but inefficient loops can slow down applications when handling large datasets.
Prefer foreach for Arrays
foreach is usually cleaner and easier to read for arrays.
Avoid Unnecessary Nested Loops
Nested loops increase execution time because each inner loop runs repeatedly.
Cache Repeated Calculations
Wrong:
<?php
for ($i = 0; $i < count($items); $i++) {
echo $items[$i];
}
?>
Better:
<?php
$total = count($items);
for ($i = 0; $i < $total; $i++) {
echo $items[$i];
}
?>
This avoids repeatedly calling count() inside the loop condition.
Infinite Loops in PHP
An infinite loop happens when the loop condition never becomes false.
Example
<?php
while (true) {
echo "Running...";
}
?>
This loop never stops unless the script is terminated manually.
Infinite loops can increase CPU usage and freeze applications.
Common Errors and Fixes
Missing Loop Increment
One of the most common mistakes is forgetting to update the loop variable.
Wrong:
<?php
$count = 1;
while ($count <= 5) {
echo $count;
}
?>
This creates an infinite loop.
Correct:
<?php
$count = 1;
while ($count <= 5) {
echo $count;
$count++;
}
?>
Using Wrong Loop Type
Using for for arrays with unknown sizes can make the code harder to read.
For arrays, foreach is usually the better choice.
Modifying Arrays During foreach
Be careful when changing array contents inside a foreach loop.
It can create unexpected behavior in some cases.
Which PHP Loop Should You Choose?
| Situation | Recommended Loop |
|---|---|
| Unknown number of iterations | while |
| Run code at least once | do while |
| Fixed number of repetitions | for |
| Loop through arrays | foreach |
Developer FAQ
Which loop is fastest in PHP?
In most practical applications, the performance difference is very small. Choose the loop that makes the code easier to read and maintain.
Can I use break inside foreach?
Yes. break works with all PHP loop types.
Can continue be used inside nested loops?
Yes. It skips the current iteration of the loop where it is used.
When should I use foreach instead of for?
Use foreach when working with arrays. It avoids manual index handling and improves readability.
Can loops affect performance?
Yes. Large nested loops and inefficient conditions can slow down applications when processing large datasets.
Conclusion
PHP loop control structures help automate repetitive tasks and simplify code.
Use while and do while for condition-based repetition, for for fixed iterations, and foreach for arrays.
The break and continue statements help control loop execution efficiently.
Choosing the correct loop makes your PHP code cleaner, easier to maintain, and more efficient.
Download Source Code
Download the complete working examples used in this tutorial:
good job
Thank you Sadi.