Posted By:
9 Mar, 2014 6:05 am PDT

How to write while loop in PHP

How to write while loop?

Very often when you write code, you always come under situation when you want to execute blocks of code repeatedly under some condition.

Syntax:-

While(condition)

{

        //write your code here

}

Statements in while() loop keep getting executed till condition is being tested remains true. In while() loop condition is evaluated first , if true , then block of code gets executed.

 
 
<?PHP
echo " <h2 > " ;
echo " To find addition of first 20 numbers !!!!! < br > < br > " ;
$result =0;
$i =1;
while ( $i <= 20)// condition
{
 $result = $result + $i ; // statements
 
 $i ++; // increment
}
 
echo " Addition of first 20 numbers { $result } " ;
?>

WhileLoop.php

 

 

WhileLoopOutput

Attachment: WhileLoop.php


How to use while loop in PHP?

 

The while loop executes a block of code as long as the given condition accordingly is true.

 

//To print the series of even numbers

 

<!DOCTYPE html>

<html>

<body>

<?php

$i=2;

$num=20;

while($i<=$num)

{

    echo $i."<br>";

    $i+=2;

}

?>

</body>

</html>

/*Output of the above program is:

2

4

6

8

10

12

14

16

18

20

*/

 

 

Attachment: while.php
Was it useful?  




Please login to reply to this problem.