The FOR Loop

PHP for loop can be used to traverse set of code for the specified number of times. For example if you want to repeat something ten or twenty times.

It should be used if number of iteration is known otherwise I recommend you to use while loop.

Syntax:

for (Initialization; Condition; Progressive)

{

//set of statements to be executed;

}

Parameters:

Initialization: Initialize the loop counter value

Condition: Check for condition. If it evaluates to TRUE, the loop continues. If FALSE then the loop ends.

Progressive: Increase / Decrease the loop counter value

Example:

for($var=1; $var<=20; $var=$var+1)

{

echo $var .” “;

}

Output:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

Example: to display 1st 20 natural numbers in drop-down list

<?php

echo “<select>”;

for($i=1; $i<=20; $i++)

{

echo ―”<option>”.$i. “</option>”;

}

echo “</select>”;

?>

Please note inside loop area we are using variable $i to display values in drop-down list as we use variable that changes slightly each time.

Leave a Reply

Your email address will not be published.

Enjoy the tutorial? Please spread the word :)

Follow by Email
Facebook
Facebook
Google+2k
Google+
http://hirdeshbhardwaj.com/2017/03/29/the-for-loop
YouTube39
YouTube