The PHP 8.5 for loop works exactly the same as in previous versions. No new syntax was introduced in PHP 8.5 for loops. It is still a counter-controlled loop used when you know how many times you want to repeat a block of code.
What is a for Loop in PHP 8.5?
A for loop in PHP is used to execute a block of code a specific number of times. It has three parts:
Initialization – Runs once before the loop starts
Condition – Checked before each iteration
Increment/Decrement – Runs after each iteration
Basic Syntax
<?php
for (initialization; condition; increment) {
// Code to execute
}?>
Basic Example 1 : Print Numbers 1 to 5
<?php
for ($i = 1; $i <= 5; $i++) {
echo $i . " ";
}
?>
Output:
1 2 3 4 5
Example 2: Count Backwards
<?php
for ($i = 5; $i >= 1; $i--) {
echo "$i... ";
}
echo "Go!";
?>
Output:
5... 4... 3... 2... 1... Go!
Example 3: Even Numbers
<?php
for ($i = 0; $i <= 10; $i += 2) {
echo $i . " ";
}
?>
Output:
0 2 4 6 8 10
Example 4: Loop Through an Array
<?php
$fruits = ["Apple", "Banana", "Mango", "Orange"];
for ($i = 0; $i < count($fruits); $i++) {
echo $fruits[$i] . "<br>";
}
?>
Output:
Apple
Banana
Mango
Orange
Example 5: Nested for Loop (Multiplication Table)
<?php
for ($i = 1; $i <= 3; $i++) {
for ($j = 1; $j <= 3; $j++) {
echo ($i * $j) . " ";
}
echo "<br>";
}
?>
Output:
1 2 3
2 4 6
3 6 9