PHP For Loop PHP

PHP For Loop  

PHP For Loop

PHP For Loop

PHP for loop can be used to traverse set of code for the specified number of times.

It should be used if number of iteration is known otherwise use while loop.

Syntax

  1. for(initialization; condition; increment/decrement){  
  2. //code to be executed  
  3. }  

Flowchart

php for loop flowchart

Example

  1. <?php  
  2. for($n=1;$n<=10;$n++){  
  3. echo "$n<br/>";  
  4. }  
  5. ?>  

Output:

1
2
3
4
5
6
7
8
9
10

PHP Nested For Loop

We can use for loop inside for loop in PHP, it is known as nested for loop.

In case of inner or nested for loop, nested for loop is executed fully for one outer for loop. If outer for loop is to be executed for 3 times and inner for loop for 3 times, inner for loop will be executed 9 times (3 times for 1st outer loop, 3 times for 2nd outer loop and 3 times for 3rd outer loop).

Example

  1. <?php  
  2. for($i=1;$i<=3;$i++){  
  3. for($j=1;$j<=3;$j++){  
  4. echo "$i   $j<br/>";  
  5. }  
  6. }  
  7. ?>  

Output:

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

PHP For Each Loop

PHP for each loop is used to traverse array elements.

Syntax

  1. foreach( $array as $var ){  
  2.  //code to be executed  
  3. }  
  4. ?>  

Example

  1. <?php  
  2. $season=array("summer","winter","spring","autumn");  
  3. foreach( $season as $arr ){  
  4.   echo "Season is: $arr<br />";  
  5. }  
  6. ?>  

Output:

Season is: summer
Season is: winter
Season is: spring
Season is: autumn

 

Download free E-book of PHP


#askProgrammers
Learn Programming for Free


Join Programmers Community on Telegram


Talk with Experienced Programmers


Just drop a message, we will solve your queries