Loops in PHP

php book written by indian author Hirdesh Bhardwaj
PHP Mysql For Advanced Learning- 2nd Edition

Loops in PHP

Loops are by far the most powerful component of PHP. A loop is simply a set of statements repeated more than once.

There may be a situation when you need to execute a block of code several number of times. But when you are running the same code over and over would produce the same result. So what is the benefit of using Loop in that case?  Basically a loop contains a variable that changes slightly each time.

 

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

The Nested For Loop: We can use for loop inside another for loop in PHP, it is known as nested for loop. In case of inner or nested loop, nested for loop is executed fully for one outer for loop.

 

Example, If outer loop is to be executed for 2 times and nested Inner loop for 2 times, then the nested inner loop will be executed 4 times (2 times for 1st outer loop and 2 times for 2nd outer loop).

Example:

 

<?php

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

{

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

{

echo $j. ” “;

}

echo “<br>”;

}

?>

 

Output

1

1 2

1 2 3

1 2 3 4

1 2 3 4 5

Enjoy the tutorial? Please spread the word :)

Follow by Email
Facebook
Facebook
Google+2k
Google+
http://hirdeshbhardwaj.com/2017/09/14/loop-in-php
YouTube41
YouTube