PHP for Loop – Step-by-Step Guide with Examples and Best Practices
Introduction: Why Loops Are Important in PHP
When you write PHP programs, you often need to repeat the same task multiple times.
For example:
Display numbers from 1 to 10
Show a list of students
Print table rows from database records
Generate repeated HTML elements
Instead of writing the same code again and again, PHP provides loops.
One of the most commonly used loops is the PHP for loop.
This guide explains the PHP for loop in a clear, teacher-style, beginner-friendly way, so you can understand it even if you are learning PHP for the first time.
What Is a for Loop in PHP?
A for loop is used when:
You know how many times a block of code should run
You want to repeat code in a controlled way
👉 In simple words:
A PHP for loop runs code again and again until a condition becomes false.
Basic Syntax of PHP for Loop
for (initialization; condition; increment/decrement) {
// Code to execute
}
Understanding Each Part (Very Simple Explanation)
| Part | Meaning |
|---|---|
| Initialization | Sets the starting value |
| Condition | Checks whether the loop should continue |
| Increment / Decrement | Changes the value after each loop |
Example 1: Print Numbers from 1 to 5
<?php
// Step 1: Initialization
for ($i = 1; $i <= 5; $i++) {
// Step 2: Action inside the loop
echo "Number: $i<br>";
}
?>
How This Works (Step-by-Step)
$i = 1→ Loop starts from 1$i <= 5→ Loop runs while this is true$i++→ Value of$iincreases by 1 each timeLoop stops when
$ibecomes 6
Example 2: Print Even Numbers Using for Loop
<?php
for ($i = 2; $i <= 10; $i += 2) {
echo $i . "<br>";
}
?>
Example 3: Print Numbers in Reverse Order
<?php
for ($i = 5; $i >= 1; $i--) {
echo $i . "<br>";
}
?>
Using PHP for Loop with HTML
The PHP for loop is often used to generate HTML dynamically.
Example: Create a List Using for Loop
<ul>
<?php
for ($i = 1; $i <= 5; $i++) {
echo "<li>Item $i</li>";
}
?>
</ul>
👉 This is commonly used in menus, tables, and lists.
Example 4: PHP for Loop Table (Multiplication Table)
<?php
$number = 5;
for ($i = 1; $i <= 10; $i++) {
echo "$number x $i = " . ($number * $i) . "<br>";
}
?>
Using for Loop with Arrays
Although foreach is preferred for arrays, for loops can still be used.
<?php
$colors = ["Red", "Green", "Blue"];
for ($i = 0; $i < count($colors); $i++) {
echo $colors[$i] . "<br>";
}
?>
When Should You Use a for Loop?
Use a for loop when:
The number of iterations is known
You need index-based control
You are working with counters
PHP for Loop vs while Loop
| Feature | for Loop | while Loop |
|---|---|---|
| Iterations known | ✅ Yes | ❌ Often unknown |
| Structure | Compact | Condition-based |
| Beginner-friendly | âś… Yes | âś… Yes |
| Common use | Counting | Dynamic conditions |
Common Beginner Mistakes
- Forgetting
$before variable - Â Using
=instead of<=in condition - Â Infinite loop (condition never becomes false)
- Â Missing increment or decrement
- Â Incorrect loop boundaries
Best Practices for Using PHP for Loop
Keep the Code Clean:
Keep the Code Clean:
- Minimize logic inside the loop to enhance readability.
- Example:
$length = count($array);
for ($i = 0; $i < $length; $i++) {
processItem($array[$i]);
}
Optimize Conditions:
Optimize Conditions:
- Avoid recalculating the array length inside the loop condition:phpÂ
// Bad practice
for ($i = 0; $i < count($array); $i++) { ... }
// Good practice
$length = count($array);
for ($i = 0; $i < $length; $i++) { ... }
Use Meaningful Variable Names:
Use Meaningful Variable Names:
- Replace generic names like
$iwith descriptive ones if the context demands it.
for ($index = 0; $index < $length; $index++) {
echo $array[$index];
}
Avoid Infinite Loops:
Avoid Infinite Loops:
- Ensure the
conditioneventually becomesfalse. For example:
for ($i = 1; $i >= 1; $i++) { // Infinite loop
echo $i;
}
Real-World Use Case Example
Display Student Numbers
<?php
for ($roll = 1; $roll <= 30; $roll++) {
echo "Student Roll No: $roll <br>";
}
?>
👉 Used in school systems, admin panels, reports, and dashboards.
FAQs: PHP for Loop
What is a for loop in PHP?
A loop that runs code a fixed number of times.
Can I skip values in a for loop?
Yes, by increasing the increment value.
What happens if I forget increment?
The loop may run infinitely.
Is for loop faster than while loop?
Performance difference is minimal in most cases.
Can I use for loop with HTML?
Yes, it is commonly used to generate HTML dynamically.