PHP For Loop
Posted on: March 26, 2010 at 12:00 AM
In this tutorial we will study about for loop,probably for loop is the most easy to understand. Examples in this tutorial will make it more clear.

For Control Structure:

In for loop construct there are three parts of For loop, first Initialization part: initialize a variable (we can initialize more than one variable at a time by using comma operator between variables), Condition: to check the validity of the condition, Increment/Decrement: we can increment or decrement the variable(s).

Format of for loop is as below:

for(variable initialization; condition; variable increment/decrement)

statements;

We can use alternative structure also, example is given below:

Example:

<?php

for($i=0;$i<=10;$i++){

echo "<b>Value of i:</b>$i<br/>";

}

echo "<p/>";

$j=10;

for(;$j>0;$j--){

echo "<b>Value of j:</b>$j<br/>";

}

$k=2;

echo "<p/>";

for(;$k<=10;){

echo "<b>Value of k:</b>$k<br/>";

$k+=2;

}

?>

 

Output:

Value of i:0
Value of i:1
Value of i:2
Value of i:3
Value of i:4
Value of i:5
Value of i:6
Value of i:7
Value of i:8
Value of i:9
Value of i:10

Value of j:10
Value of j:9
Value of j:8
Value of j:7
Value of j:6
Value of j:5
Value of j:4
Value of j:3
Value of j:2
Value of j:1

Value of k:2
Value of k:4
Value of k:6
Value of k:8
Value of k:10

Example:

<?php

for($a=1;$a<=10;$a++):

echo $a."&nbsp;";

endfor;

?>

Output:

1 2 3 4 5 6 7 8 9 10 

Related Tags for PHP For Loop:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.