PHP is a popular server-side scripting language used for web development. One of the fundamental constructs in PHP (and many other programming languages) is the for loop, which allows you to execute a block of code repeatedly for a specified number of times. In this blog post, we will explore the for loop in PHP and provide examples to demonstrate its usage.
Syntax of the for loop
The syntax of the for loop in PHP is as follows:
for (initialization; condition; increment/decrement) {
// block of code to be executed
}
Let’s examine each part of the for loop syntax in detail:
- Initialization: This statement is executed only once, at the beginning of the loop. It is used to set the initial value of the loop counter variable.
- Condition: This is an expression that is evaluated before each iteration of the loop. If the expression is true, the loop continues; if it is false, the loop terminates.
- Increment/decrement: This statement is executed after each iteration of the loop. It is used to modify the value of the loop counter variable.
- Block of code: This is the code that is executed repeatedly for the specified number of times.
Example 1: Printing numbers from 1 to 10 using For Loop in PHP
Let’s start with a simple example that demonstrates how to use the for loop to print numbers from 1 to 10:
for ($i = 1; $i <= 10; $i++) {
echo $i . " ";
}
In this example, we initialize the loop counter variable $i
to 1. The condition checks whether $i
is less than or equal to 10, and the loop continues as long as the condition is true. The increment statement $i++
increments the value of $i
by 1 after each iteration. Inside the block of code, we use the echo
statement to print the value of $i
followed by a space.
The output of this code is:
1 2 3 4 5 6 7 8 9 10
Example 2: Calculating the sum of numbers from 1 to 100 using For Loop in PHP
Let’s take another example that demonstrates how to use the for loop to calculate the sum of numbers from 1 to 100:
$sum = 0;
for ($i = 1; $i <= 100; $i++) {
$sum += $i;
}
echo "The sum of numbers from 1 to 100 is: " . $sum;
In this example, we initialize the loop counter variable $i
to 1 and the variable $sum
to 0. The condition checks whether $i
is less than or equal to 100, and the loop continues as long as the condition is true. Inside the block of code, we use the +=
operator to add the value of $i
to $sum
in each iteration.
The output of this code is:
The sum of numbers from 1 to 100 is: 5050