Share on Google+Share on Google+

PHP For Loop Function

Advertisement
In this current php tutorial we will study about for loop using in PHP program. We will study about different formats of for loop, how to initialize the variable inside the loop, condition checking, changing the value of the variable etc. In for loop construct there are three parts...

For loop Function in PHP:

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).

For loop function 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

Explanation:

Generally we follow the natural construct of for loop but we can modify it according to our need like we can initialize the variable outside the body of the loop, we can change the value of the variable (increase or decrease the value of the variable), inside the loop. Above examples could clear this point. 

Advertisements

Advertisement

Posted on: February 15, 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.