The for loop is used when you know in advance how many times the script should run. It gathers the initialization, condition, and increment logic into a single line, making your code extremely concise.
The for loop takes three parameters, separated by semicolons:
for (init counter; test counter; increment counter) {
// code to be executed for each iteration;
}
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
You can also use the for loop to count down by using a decrement operator.
<?php
for ($x = 10; $x >= 0; $x--) {
echo "Countdown: $x <br>";
}
?>
The increment part doesn't have to be $x++. You can increase by any value you wish.
<?php
for ($x = 0; $x <= 100; $x += 10) {
echo "Step: $x <br>";
}
?>
for loop can be left empty (e.g., for (;;)), but you must still provide the semicolons.
for loop whenever the number of iterations is fixed, such as printing the days of a month or headers for a table.
$x += 5).$x <= count($arr) instead of $x < count($arr) reads one index past the end of an array, producing an undefined-index warning.
count($arr) directly inside the loop condition re-runs it every pass. Store it in a variable first if the array won't change size during the loop.
A second example that does real work inside the loop instead of just printing values:
<?php
$sum = 0;
for ($x = 2; $x <= 20; $x += 2) {
$sum += $x;
}
echo "Sum of even numbers 1-20: $sum"; // 110
?>
Q: What's the difference between for and foreach?
A: for is best with a numeric counter and a known range; foreach is designed specifically for iterating over arrays without manually tracking an index.
Q: Can I loop through a string with a for loop?
A: Yes — use strlen($str) for the bound and $str[$i] to access each character by position.
Q: What happens if I write an infinite for loop in PHP?
A: The script keeps running until it hits the server's max_execution_time setting, then PHP fatally errors out. See the PHP manual's for loop reference for the exact evaluation order.