Posted By:
8 Mar, 2014 2:19 am PST

How to write for loop in php?

 How to write for loop in php?

This loop is most widely used in any programming language. for() loop specifies three things: i.e., first setting loop counter to an initial value second testing loop condition and last one incrementing/decrementing loop counter value.

Syntax:-

for(initialization; condition; updating)

{

//write your code here

}

<?php

echo "<h2 >"; 

echo "To find Fibonacci series of first 10 numbers <br ><br >";

$num1 =0; 

$num2 =1; 

echo " Fibonacci series of first 10 Number is as follows <br ><br >";

echo "{ $num2 }";

                for( $i =0; $i < 10; $i ++)

                // initialization ; condition ;increment

{ 

         $fs = $num1 + $num2 ;// statements 

$num1 = $num2 ;

$num2 = $fs; 

echo " { $fs } "; 

}

?>

Initialization section executed only once , when loop start executing for first time. Then condition is tested , then block of code gets executed. After this updating section gets executed once again condition is tested and so on. 

ForLoopOutput

Attachment: ForLoop.php


How to use for loop in PHP?

 

for loop is used when you know in advance how many times it should be run.that is it is known to the programmer how many times loop should be run.

 

//Program to print the following pattern using PHP

*

**

***

**** 

 

<!DOCTYPE html>

<html>

<body>

<?php

   for($i=0;$i<4;$i++)

   {

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

       {

       echo "*";

   }

   echo "<br>";

   }

?>

</body>

<html>

 

/*Output of the above program is the given pattern

*

**

***

****    

*/

 

Attachment: for.php
Was it useful?  




Please login to reply to this problem.