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.
PHP For loop
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 . " ";
}
- In this example, we start with $i initialized to 1 ($i = 1).
- The loop continues as long as $i is less than or equal to 5 ($i <= 5).
- In each iteration, $i is incremented by 1 ($i++).
- The echo statement prints the value of $i followed by a space.
- This loop will execute five times, printing "1 2 3 4 5 ".
Iterating Backwards from 10 to 1
for ($i = 10; $i >= 1; $i--) {
echo $i . " ";
}
- Here, we initialize $i to 10 ($i = 10).
- The loop continues as long as $i is greater than or equal to 1 ($i >= 1).
- In each iteration, $i is decremented by 1 ($i--).
- The echo statement prints the value of $i followed by a space.
- This loop will execute ten times, printing "10 9 8 7 6 5 4 3 2 1 ".
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;
- In this example, we start with a variable $sum initialized to 0.
- The loop is used to iterate through even numbers from 2 to 10.
- We increment $i by 2 in each iteration ($i += 2), ensuring that we only consider even numbers.
- Inside the loop, we add the value of $i to the $sum variable.
- After the loop completes, we print the sum of even numbers.
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.
×