PHP for Loop
In this page:
What is a for Loop?
A for loop is the right tool when you know in advance how many times you need to repeat something. Its header packs three parts into one line — where the counter starts, the condition that keeps the loop going, and how the counter changes after each pass.
Example: What is a for Loop?
<?php
for ($i = 1; $i <= 5; $i++) {
echo $i . "\n";
}
?>
Login to try C/C++/Java/PHP code in the editor
Custom Loop Steps
The step (increment) expression in a for loop's header isn't locked to adding 1 — you can add 2 to skip every other value, multiply for exponential steps, or use any expression at all, as long as it eventually makes the loop's condition become false.
Example: Custom Loop Steps
<?php
for ($i = 0; $i <= 10; $i += 2) {
echo $i . "\n";
}
?>
Login to try C/C++/Java/PHP code in the editor
Looping Through Indexed Arrays
Using the loop counter directly as an array index ($array[$i]) is exactly why for loops pair so naturally with arrays — you get both the current position and the corresponding value in every single iteration, without any extra bookkeeping.
Example: Looping Through Indexed Arrays
<?php
$fruits = ["apple", "banana", "cherry"];
for ($i = 0; $i < count($fruits); $i++) {
echo $i . ": " . $fruits[$i] . "\n";
}
?>
Login to try C/C++/Java/PHP code in the editor
Nested for Loops
One for loop nested inside another runs the inner loop to full completion for every single iteration of the outer one — the classic pattern for anything grid-shaped, like printing a multiplication table or walking a 2D array's rows and columns.
Example: Nested for Loops
<?php
for ($i = 1; $i <= 2; $i++) {
for ($j = 1; $j <= 2; $j++) {
echo "$i x $j = " . ($i * $j) . "\n";
}
}
?>
Login to try C/C++/Java/PHP code in the editor
Alternative Syntax
PHP's alternative syntax swaps the opening { for a colon and the closing } for endfor;, which — exactly as with if and while — keeps a loop far more readable when its body is interleaved with HTML output in a template.
Example: Alternative Syntax
<?php for ($i = 1; $i <= 3; $i++): ?>
<p>Row <?php echo $i; ?></p>
<?php endfor; ?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: