The while statement will execute a block of code if and as long as a test expression is true. If the test expression is true then the code block will be executed. After the code has executed the test expression will again be evaluated and the loop will continue until the test expression is found to be false.
Syntax
while (condition is true) { code to be executed; }
In the example below first sets a variable $x to 1 ($x = 1). Then, the while loop will continue to run as long as $x is less than, or equal to 5 ($x <= 5). $x will increase by 1 each time the loop runs ($x++)
<?php $x = 1; while($x <= 5) { echo "The number is: $x <br>"; $x++; } ?>
Output
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
In the below example it decrements a variable value on each iteration of the loop and the counter increments until it reaches 10 when the evaluation is false and the loop ends.
<?php $i = 0; $num = 50; while( $i < 10) { $num--; $i++; } echo ("Loop stopped at i = $i and num = $num" ); ?>
Output: Loop stopped at i = 10 and num = 40
Example to find the sum of 1 to 100 using While Loop
<?php $i=1; $sum=0; while($i<=100) { $sum=$sum+$i; $i++; } echo "Sum= " . $sum; ?>
Output: Sum= 5050