php for loop

For loop is used to execute a block of code for a specified amount of times The for loop is less prone to generating an infinite loop because you are required to declare all the conditions of the loop in the first line.

For loop Syntax :

<?php
for (initialize counter; test; increment)
{
//code to be executed
}
?>

initialize

counter this parameters used to initialize variable value.

test

this parameters used to control the loop.

Increment

this parameters used for loop Increment.

For loop Example :


<?php
for ($i = 1; $i <= 100; $i++)
{
echo "$i";
}
?>

The above code is displaying number is 1 to 100.

The three expressions inside the parentheses control the action of the loop (note that they are separated by semicolons, not commas):

  • The first expression shows the starting point. You can use any variable you like, but the convention is to use $i. When more than one counter is needed, $j and $k are frequently used.
  • The second expression is a test that determines whether the loop should continue to run. This can be a fixed number, a variable, or an expression that calculates a value.
  • The third expression shows the method of stepping through the loop. Most of the time, you will want to go through a loop one step at a time, so using the increment (++) or decrement (--) operator is convenient. There is nothing stopping you from using bigger steps.




Content