Loops (while, for, foreach)
In many real-world applications, you often need to repeat a block of code multiple times — whether it’s displaying a list of users, processing data, or generating dynamic content. Writing the same code repeatedly is inefficient, and that’s where loops come in.
In this lesson, you’ll learn how to use loops in PHP, including while, for, foreach, and do...while. By the end, you’ll be able to efficiently repeat tasks and work with arrays in your applications.
What are Loops in PHP?
Loops allow you to execute a block of code multiple times based on a condition. Instead of writing repetitive code manually, you define a loop that runs until a condition is no longer true.
The while Loop
The while loop executes a block of code as long as a condition remains true.
Syntax
while (condition) {
// code to execute
}
Example
$i = 1;
while ($i <= 5) {
echo $i . " ";
$i++;
}
Output:
1 2 3 4 5
Use case:
Use while when you don’t know in advance how many times the loop should run.
The do...while Loop
The do...while loop is similar to while, but it always executes the code at least once, even if the condition is false from the start.
Syntax
do {
// code to execute
} while (condition);
Example
$i = 10;
do {
echo $i;
$i++;
} while ($i <= 5);
Output:
10
Use case:
Useful in scenarios like retry logic, menu-driven programs, or form handling where the code must run at least once.
The for Loop
The for loop is used when you know exactly how many times you want to run a block of code.
Syntax
for (initialization; condition; increment) {
// code to execute
}
Example
for ($i = 1; $i <= 5; $i++) {
echo $i . " ";
}
Output:
1 2 3 4 5
Use case:
Ideal for counting loops, such as iterating a fixed number of times.
The foreach Loop
The foreach loop is specifically designed for working with arrays. It allows you to loop through each element in an array easily.
Example
$colors = ["red", "blue", "green"];
foreach ($colors as $color) {
echo $color . " ";
}
Output:
red blue green
Associative Array Example
$user = [
"name" => "Rohan",
"age" => 22
];
foreach ($user as $key => $value) {
echo $key . ": " . $value . " ";
}
Output:
name: Rohan age: 22
Explanation:
In real applications, associative arrays are often used for data like database records, where keys represent column names such as name or age.
Use case:
Best for looping through arrays, especially when working with database results or structured data.
Key Differences: while vs for vs foreach
Loop Type | Best Use Case | When to Use --------- | -------------------------- | ----------------------------- while | Unknown iterations | Condition-based loops for | Fixed number of iterations | Counting loops foreach | Arrays | Looping through collections
Best Practice
Prefer foreach when working with arrays because it is more readable and less error-prone compared to manual indexing with for.
Common Mistakes Beginners Make
1. Infinite Loop (Missing Increment)
$i = 1;
while ($i <= 5) {
echo $i;
}
Why it fails:
The loop never stops because $i is never updated.
Correct version:
$i = 1;
while ($i <= 5) {
echo $i;
$i++; // Fix
}
2. Wrong Loop Condition
for ($i = 1; $i >= 5; $i++) {
Why it fails:
The condition is incorrect, so the loop may never execute.
3. Modifying Array While Looping
foreach ($colors as $color) {
$colors[] = "new";
}
Why it’s risky:
This can lead to unexpected behavior or infinite loops.
Real-World Example
$prices = [100, 200, 300];
$total = 0;
foreach ($prices as $price) {
$total += $price;
}
echo "Total Price: ₹" . $total;
Output:
Total Price: ₹600
What this shows:
- Looping through array (
foreach) - Arithmetic operation (
+=) - Real-world use case (cart total calculation)
Practice Exercise
Task 1
Print numbers from 1 to 5 using a loop.
Expected Output:
1 2 3 4 5
Task 2
Loop through an array of 3 names and print them.
Expected Output:
Rohan Amit Rahul
Task 3
Calculate the sum of numbers in an array.
Expected Output:
600
Summary
In this lesson, you learned how loops work in PHP using while, for, foreach, and do...while. These loops allow you to repeat tasks efficiently and handle collections of data like arrays.
Mastering loops is essential for building dynamic applications such as dashboards, reports, and data-driven features.