Google News
logo
PHP while Loop
The PHP  while loop executes a block of code as long as the specified condition is true.
Syntax
while (condition)
{
   // code to be executed;
Example :
<!DOCTYPE html>
<html>
<head>
	<title>PHP While Loop</title>
</head>

<body>

<?php
	$i=1;
	while($i<=5)  
	{  
	echo "The number is : " . $i . "<br />";  
	$i++;  
	}  
?>

</body>
</html>
Output :

In the above example $i hold the value=1, now check the condition while value of ($i<=5). it means execute the code five times. It print the statement line by line.

Another Example
<!DOCTYPE html>
<html>
<head>
	<title>PHP While Loop</title>
</head>

<body>

<?php	
	$i=1;	
	$sum=0;	
	while($i<=27)	 
	{	  
	$sum=$sum+$i;	  
	$i++;	  
	}		
	echo "Sum= " . $sum;	 
?>

</body>
</html>
Output :

In the above example Variable $i hold value=1, initially $sum hold value=0. we want to sum of 1 to 27 number using while loop. It execute the statement ($sum=$sum+$i;) till the condition is true and value is increment by ($i++). so it will give the output is 378.

PHP do...while Loop

The PHP do...while loop will always execute the block of code once, and then the condition is evaluated, and the statement is repeated as long as the specified condition evaluated to is true.

Syntax
do {
    //code to be executed;
} while (condition is true);
Example :
<!DOCTYPE html>
<html>
<head>
	<title>PHP do...while Loop</title>
</head>

<body>

<?php	
	$i=1;	
	do	 
	 {	  
		echo "The number is : " . $i . "<br />";	 
	    $i++;	  
	}while ($i<=5); 	
	
?>

</body>
</html>
Output :

In the above example variable $i hold value=1. first execute the statement inside do. After it check while condition ($i<=5). So the given statements execute 5 times.

PHP Break Statement
PHP break statement breaks the execution of current for, while, do-while, switch and for-each loop. If you use break inside inner loop, it breaks the execution of inner loop only.
Syntax

jump statement;

break;

Break - inside loop
<!DOCTYPE html>
<html>
<head>
	<title>PHP Break Statement - inside Loop</title>
</head>

<body>

<?php  
	for($i=1;$i<=10;$i++){  
		echo "$i <br />";  
		if($i==5){  
		break;  
		}  
	}  
?>  

</body>
</html>
Output :
Break - inside inner loop
The PHP break statement breaks the execution of inner loop only.
<!DOCTYPE html>
<html>
<head>
	<title>PHP Break Statement - inside Loop</title>
</head>

<body>

<?php  
	for($i=1;$i<=10;$i++){  
		echo "$i <br />";  
		if($i==5){  
		break;  
		}  
	}  
?>  

</body>
</html>
Output :