Share on Google+Share on Google+

PHP For Loop

Advertisement
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 

Advertisements

Posted on: March 26, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.