for in PHP loop programming

for statement is also used to make looping in PHP programming. Its structure is bit more complex than the other loop statements like “while”.

Its structure will look like

for ( expression 1 ; expression 2 ; expression 3 )
{
// Operation statements
}

In “for statement”

  • expression 1 will evaluate before the beginning of loop
  • expression 2 will evaluate before the beginning of each iteration
  • expression 3 will evaluate at the end of each iteration

See the sample program with for statement in PHP

<?php
for ($i=0 ; $i < 10 ; $i++)
{
echo $i." ";
}
?>

Its output will be
0 1 2 3 4 5 6 7 8 9

In this example the first expression ($i=0) will execute before the “for loop”.
Then it will execute the second expression ($i < 10) before each iteration.
At the end of each iteration third expression ($i++) will execute.

The expressions with “for statement” can be empty.
See this PHP program will give the same output like the previous example

<?php
$i=0;
for ( ; $i < 10 ; $i++)
{
echo $i." ";
}
?>

Its output will be :
0 1 2 3 4 5 6 7 8 9

And we can see that the first expression is empty in “for statement”.

Share