PHP While Loop

The PHP while loop is used to repeat the code inside the while loop a specific number of times. The conditional statement decides the number of iterations of the code. If the condition is TRUE, the while loop continues to execute the code, and if the condition is FALSE, the control move outside of the while loop.

While the loop at the beginning evaluates the conditional expression similar to the if statement and executes the subsequent code block inside the loop, the condition will be checked first before executing the code.

After the code execution, PHP passes control back at the beginning to check the conditional statement.

If it is TRUE, the same process is followed. If it is false loop is terminated.

In the case of a while loop, the code may not execute even once if the condition is FALSE in the first place.

			

While ( The conditional expression)
{
	//Execution of the code.
}

				

Here is an example of code that prints the incremental value of variable $var.

			

<?php
$var = 1;
While ( $var < 5 )
{
	echo "The variable value is " . $var . "</br>";
}
?>

				

Output:

The variable value is 1 The variable value is 2 The variable value is 3 The variable value is 4

The PHP do-while loop is often used when unsure about the number of iterations required to get the desired result.