0
0
PhpHow-ToBeginner · 3 min read

How to Use For Loop in PHP: Syntax and Examples

In PHP, a for loop repeats a block of code a set number of times using three parts: initialization, condition, and increment. The loop runs as long as the condition is true, making it useful for counting or repeating tasks.
📐

Syntax

The for loop in PHP has three main parts inside parentheses, separated by semicolons:

  • Initialization: Sets the starting point, usually a variable.
  • Condition: Checked before each loop; if true, the loop runs.
  • Increment/Decrement: Changes the variable each time the loop runs.

The code inside curly braces { } runs each time the loop repeats.

php
for (initialization; condition; increment) {
    // code to repeat
}
💻

Example

This example prints numbers from 1 to 5 using a for loop. It shows how the loop starts at 1, checks if the number is less than or equal to 5, prints the number, then adds 1 to the number each time.

php
<?php
for ($i = 1; $i <= 5; $i++) {
    echo $i . "\n";
}
?>
Output
1 2 3 4 5
⚠️

Common Pitfalls

Common mistakes when using for loops include:

  • Forgetting to update the loop variable, causing an infinite loop.
  • Using the wrong comparison operator, so the loop never runs or runs too long.
  • Initializing the variable outside the loop but not resetting it properly.

Always make sure the condition will eventually become false to stop the loop.

php
<?php
// Wrong: Infinite loop because $i is never incremented
for ($i = 1; $i <= 5;) {
    echo $i . "\n";
}

// Right: Increment $i to avoid infinite loop
for ($i = 1; $i <= 5; $i++) {
    echo $i . "\n";
}
?>
📊

Quick Reference

PartDescriptionExample
InitializationSet starting value$i = 0
ConditionLoop runs while true$i < 10
IncrementChange value each loop$i++ or $i += 2

Key Takeaways

Use the for loop to repeat code a fixed number of times with initialization, condition, and increment.
Always update the loop variable to avoid infinite loops.
The loop runs only while the condition is true.
Use echo inside the loop to output values each time it runs.
Check your condition carefully to control how many times the loop executes.