PHP Loops — Complete Guide to for, while, foreach, and Loop Control
In this tutorial, you will learn about PHP Loops. We cover key concepts, practical examples, and best practices to help you master this topic.
PHP loops execute code repeatedly based on conditions, with for, while, do-while, and foreach providing different iteration patterns for various scenarios.
What You'll Learn
By the end of this tutorial, you'll use for, while, do-while, and foreach loops, control execution with break and continue, iterate over arrays, and avoid infinite loop bugs.
Why Loops Matter
Loops Process collections of data, generate repetitive output, and automate tasks that would require manual repetition. Almost every PHP script uses loops for data processing.
Real-World Use
An e-commerce site uses foreach to iterate over cart items and display them, a for loop to generate pagination links, and a while loop to process database result sets.
PHP Loops Learning Path
flowchart LR
A[Boolean Logic] --> B[Loops]
B --> C[Functions]
C --> D[Arrays]
D --> E[Forms]
A --> F{You Are Here}
style F fill:#f90,color:#fff
For Loop
<?php
for ($i = 0; $i < 5; $i++) {
echo $i . " ";
}
// Output: 0 1 2 3 4
// Multiple counters
for ($i = 0, $j = 10; $i < 5; $i++, $j--) {
echo "($i, $j) ";
}
// Output: (0, 10) (1, 9) (2, 8) (3, 7) (4, 6)
While Loop
<?php
$count = 0;
while ($count < 5) {
echo $count . " ";
$count++;
}
// Output: 0 1 2 3 4
Do-While Loop
<?php
$i = 0;
do {
echo $i . " ";
$i++;
} while ($i < 5);
// Output: 0 1 2 3 4
// Always executes at least once
$i = 10;
do {
echo "This runs once"; // Executes even though condition is false
} while ($i < 5);
Foreach Loop
<?php
$colors = ["red", "green", "blue"];
foreach ($colors as $color) {
echo $color . " ";
}
// Output: red green blue
// With keys
$user = ["name" => "Alice", "age" => 25, "city" => "Mumbai"];
foreach ($user as $key => $value) {
echo "$key: $value, ";
}
// Output: name: Alice, age: 25, city: Mumbai,
Break and Continue
<?php
for ($i = 0; $i < 10; $i++) {
if ($i === 3) continue; // Skip 3
if ($i === 7) break; // Stop at 7
echo $i . " ";
}
// Output: 0 1 2 4 5 6
// Break with depth
for ($i = 0; $i < 3; $i++) {
for ($j = 0; $j < 3; $j++) {
if ($i === 1 && $j === 1) break 2; // Break both loops
echo "($i,$j) ";
}
}
// Output: (0,0) (0,1) (0,2) (1,0)
Array Iteration Patterns
<?php
$products = [
["name" => "Laptop", "price" => 999],
["name" => "Mouse", "price" => 25],
["name" => "Keyboard", "price" => 75]
];
foreach ($products as $product) {
echo "{$product['name']}: \${$product['price']}\n";
}
Common Mistakes
1. Infinite Loops
Forgetting to increment the counter: for ($i = 0; $i < 10;) or while (true) without break.
2. Modifying Array While Iterating
Adding or removing elements during foreach can produce unexpected results. Iterate over a copy.
3. Off-by-One Errors
for ($i = 0; $i <= 5; $i++) iterates 6 times, not 5. Use < for zero-based indices.
4. Using foreach on Non-Arrays
foreach expects arrays or Traversable objects. Pass it null or a string and it errors.
5. Nested Loop Performance
Nested loops with large datasets are slow. Consider alternative approaches like hash lookups.
Practice Questions
1. What is the difference between while and do-while?
while checks the condition before execution. do-while checks after, guaranteeing at least one execution.
2. What does foreach ($array as $key => $value) do?
It iterates over each element, assigning the key to $key and the value to $value for each iteration.
3. How do you exit a loop early?
Use break. break 2 exits two levels of nested loops.
4. How do you skip to the next iteration?
Use continue. It jumps to the next iteration without executing the rest of the current loop body.
5. Challenge: Write a loop that prints a multiplication table (1-5) using nested loops.
<?php
for ($i = 1; $i <= 5; $i++) {
for ($j = 1; $j <= 5; $j++) {
printf("%3d ", $i * $j);
}
echo "\n";
}
// Output:
// 1 2 3 4 5
// 2 4 6 8 10
// 3 6 9 12 15
// 4 8 12 16 20
// 5 10 15 20 25
FAQ
Mini Project: Data Table Renderer
Build a function that renders HTML tables from data arrays using loops.
<?php
function renderTable(array $data): string {
if (empty($data)) return "<p>No data</p>";
$html = "<table border='1'>\n<thead>\n<tr>\n";
foreach (array_keys($data[0]) as $header) {
$html .= "<th>" . htmlspecialchars($header) . "</th>\n";
}
$html .= "</tr>\n</thead>\n<tbody>\n";
foreach ($data as $row) {
$html .= "<tr>\n";
foreach ($row as $cell) {
$html .= "<td>" . htmlspecialchars((string)$cell) . "</td>\n";
}
$html .= "</tr>\n";
}
return $html . "</tbody>\n</table>";
}
$users = [["name" => "Alice", "age" => 25], ["name" => "Bob", "age" => 30]];
echo renderTable($users);
What's Next
PHP Functions PHP Arrays PHP Include Require
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro