codescracker


php

PHP while Loop



« Previous Tutorial Next Tutorial »


PHP while loop is used to execute a block of code if and as long as the expression given evaluates to true. Here is the general form to use while loop in PHP:

while(condition)
{
	code to be executed here, if the condition evaluates to true;
	incrementation;
}

PHP while Loop Example

Here is an example, uses while loop in PHP. This example decrements a variable value on each iteration of the while loop and the counter increments until it reaches to 0 when the evaluation is false and the loop goes to end.

<html>
<head>
	<title>PHP while Loop Example - CodesCracker</title>
</head>
<body>
<?php
	$i = 25;
	while($i > 0)
	{
		$i--;
		echo $i." ";
	}
	echo "Fire!!!<br/>";
	echo "Loop stopped at i = ".$i;
?>
</body>
</html>

It will display the following result:

PHP while loop

Here is another example demonstrating while loop in PHP.

<html>
<head>
	<title>PHP while Loop Example - CodesCracker</title>
</head>
<body>
<?php
	$num = 2;
	$i = 1;
	while($i<=10)
	{
		echo $num * $i;
		echo "<br/>";
		$i++;
	}
?>
</body>
</html>

Here is the sample output of the above while loop example code.

while loop in php

Below is another example in PHP demonstrates while loop.

<html>
<head>
	<title>PHP while Loop Example - CodesCracker</title>
</head>
<body>
<?php
	$chk = true;
	$sum = 0;
	$count = 0;
	while($chk)
	{
		if($sum === 500)
		{
			$chk = false;
		}
		else 
		{
			$sum += 10;
		}
		$count++;
	}
	$count--;
	echo "Sum = ". $sum;
	echo "<br>";
	// below line prints the total number of time, the condition
	// has been checked
	// or the total number of time, program control goes 
	// inside the while loop block to execute its content
	echo "Total number of run time = ". $count;
?>
</body>
</html>

Below is the output produced by the above example code of while loop.

while loop example php

« Previous Tutorial Next Tutorial »








Tools
Calculator

Quick Links
Signup - Login - Give Online Test