The for statement is used when you know how many times you want to execute a statement or a block of statements.
Syntax
for (initialization; condition; increment)
{
code to be executed;
}
Parameters of for loop
- Initialization: is used to set a counter
- Condition: if condition is true loop will continue, if the condition is false loop ends
- Increment: used to increment the counter.
The example below displays the numbers from 0 to 10
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
Output:
The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The number is: 6
The number is: 7
The number is: 8
The number is: 9
The number is: 10
Example to makes five iterations and changes the assigned value of two variables on each pass of the loop
<?php
$a = 0;
$b = 0;
for( $i = 0; $i<5; $i++ ) {
$a += 10;
$b += 5;
}
echo ("At the end of the loop a = $a and b = $b" );
?>
Output: At the end of the loop a = 50 and b = 25
Example to Find the Sum of even and odd numbers between 1 to 100
<?php
for ($i=1; $i<=100; $i++)
{
if($i%2==0)
{
@$even=$even+$i;
}
else
{
@$odd=$odd+$i;
}
}
echo "Sum of even numbers=".$even."<br/>";
echo "Sum of odd numbers=".$odd;
?>
Output:
Sum of even numbers=2550
Sum of odd numbers=2500