Loops in PHP – Repeating Code Efficiently
What Are Loops in PHP?
Loops allow you to execute a block of code repeatedly, either a set number of times or while a certain condition is true.
They are essential in many real-world scenarios:
- Displaying a list of items from a database
- Processing form inputs
- Automating repetitive tasks (e.g., sending emails)
- Creating dynamic tables, charts, and HTML elements
The while
Loop
The while
loop runs as long as a specified condition is true.
Syntax:
while (condition) {
// code to execute
}
Example:
<?php
$count = 1;
while ($count <= 5) {
echo "Number: $count<br>";
$count++;
}
?>
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Great for situations where you don’t know in advance how many times the loop should run.
The do...while
Loop
This loop will always run at least once, even if the condition is false.
Syntax:
do {
// code to execute
} while (condition);
Example:
<?php
$attempt = 1;
do {
echo "Login attempt $attempt<br>";
$attempt++;
} while ($attempt <= 3);
?>
Output:
Login attempt 1
Login attempt 2
Login attempt 3
Useful for input prompts or retry operations where the action must occur before checking a condition.
The for
Loop
The for
loop is ideal when the number of repetitions is known.
Syntax:
for (initialization; condition; increment) {
// code to execute
}
Example:
<?php
for ($i = 1; $i <= 10; $i++) {
echo "Row $i<br>";
}
?>
Output:
Row 1
Row 2
...
Row 10
Excellent for working with numeric ranges or indexed loops.
The foreach
Loop
foreach
is used specifically for arrays. It loops through each item in the array automatically.
Syntax:
foreach ($array as $value) {
// code using $value
}
Example:
<?php
$colors = ["Red", "Green", "Blue"];
foreach ($colors as $color) {
echo "Color: $color<br>";
}
?>
Output:
Color: Red
Color: Green
Color: Blue
You can also get both key and value:
foreach ($colors as $index => $color) {
echo "Index $index: $color<br>";
}
Using break
and continue
break
: Exits the loop completelycontinue
: Skips the current iteration and continues with the next one
Example: break
<?php
for ($i = 1; $i <= 10; $i++) {
if ($i == 5) break;
echo "$i<br>";
}
?>
Output:
1
2
3
4
Example: continue
<?php
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) continue;
echo "$i<br>";
}
?>
Output:
1
2
4
5
Real-World Loop Examples
Example: Generate a Dropdown with Years
<?php
echo "<select>";
for ($year = 2000; $year <= 2025; $year++) {
echo "<option>$year</option>";
}
echo "</select>";
?>
Example: Sum All Even Numbers from 1 to 50
<?php
$sum = 0;
for ($i = 1; $i <= 50; $i++) {
if ($i % 2 == 0) {
$sum += $i;
}
}
echo "Total: $sum";
?>
Best Practices
- Initialize loop variables properly
- Avoid infinite loops — always ensure the condition will eventually be false
- Use
foreach
for arrays instead offor
with indexes - Keep loops efficient and avoid heavy computations inside them
- Minimize nesting (loop within loop) where possible
Common Mistakes to Avoid
- Forgetting to increment in
while
orfor
loop - Using the wrong loop type for the task (e.g.,
for
instead offoreach
) - Accidentally creating infinite loops
- Not resetting counters properly
Notes:
- Use
while
when the number of iterations is unknown - Use
do...while
to ensure at least one execution - Use
for
when the number of iterations is fixed - Use
foreach
to loop through arrays efficiently - Use
break
to exit early andcontinue
to skip an iteration
Practice Tasks
✅ Task 1: Count Multiples of 5
Loop from 1 to 100 and print all numbers that are divisible by 5.
✅ Task 2: Loop Through an Array
Create an array of your favorite programming languages and print each using foreach
.
✅ Task 3: Star Pattern Generator
Use nested for
loops to create this:
*
**
***
****
*****
💡 Explore More PHP Learning Tools & Resources
PHP Practice Quiz
Test your PHP skills with real coding questions and scoring.
PHP Interview Questions
Prepare for interviews with common PHP questions and answers.
Educational AI Tutor
Ask PHP questions and get instant AI-powered explanations.
Question Generator
Auto-generate PHP interview questions for quick practice.