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)

PartMeaning
InitializationSets the starting value
ConditionChecks whether the loop should continue
Increment / DecrementChanges 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)

  1. $i = 1 → Loop starts from 1

  2. $i <= 5 → Loop runs while this is true

  3. $i++ → Value of $i increases by 1 each time

  4. Loop stops when $i becomes 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

Featurefor Loopwhile Loop
Iterations known✅ Yes❌ Often unknown
StructureCompactCondition-based
Beginner-friendlyâś… Yesâś… Yes
Common useCountingDynamic 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:

  • 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:

  • Replace generic names like $i with descriptive ones if the context demands it.
for ($index = 0; $index < $length; $index++) {
    echo $array[$index];
}

Avoid Infinite Loops:

  • Ensure the condition eventually becomes false. 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>";
}
?>
  1. 👉 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.