start learning
Image 1
530104070112

PHP For loop

A PHP for loop is a control structure used to execute a block of code repeatedly for a specified number of times. It consists of three parts: initialization, condition, and increment (or decrement), and it continues to execute as long as the condition is true.


Basic Syntax of a For Loop

The basic syntax of an "For" Loop in PHP is as follows:


for (initialization; condition; increment/decrement) {
    // Code to be executed in each iteration
}
 

Counting from 1 to 5


for ($i = 1; $i <= 5; $i++) {
    echo $i . " ";
}
 


Iterating Backwards from 10 to 1


for ($i = 10; $i >= 1; $i--) {
    echo $i . " ";
}
 


Calculating the Sum of Even Numbers from 1 to 10


$sum = 0;

for ($i = 2; $i <= 10; $i += 2) {
    $sum += $i;
}
echo "Sum of even numbers from 1 to 10: " . $sum;
 


These examples demonstrate how PHP for loops work and how they can be used to perform tasks such as counting, iterating backward, and calculating sums within a specified range.


×