while loop 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.
while (condition is true) {
code to be executed;
}
while(condition):
//code to be executed
endwhile;
The block of code associated with the While statement is always enclosed within the { opening and } closing brace symbols to tell PHP clearly which lines of code should be looped through.
While loops are most often used to increment a list where there is no known limit to the number of iterations of the loop. For example:
While Looping Syntax Example:
while (there are still rows to read from a database)
{
read in a row;
move to the next row;
}
The example below first sets a variable $val to 1 ($val = 1). Then, the while loop will continue to run as long as $val is less than, or equal to 5 ($val <= 5). $val will increase by 1 each time the loop runs ($val++):
<html>
<body>
<?php
$val = 1;
while($val <= 3) {
echo "The number is: $val <br>";
$val++;
}
?>
</body>
</html>
Output :
The number is: 1
The number is: 2
The number is: 3
© 2024 Easy To Learning. All Rights Reserved | Design by Easy To Learning