PHP while loop is used to execute statement/s if the condition is true until a certain condition is false. Always remember that a conditional statement returns a boolean value which is either true or false. Once true, it will execute the code inside the loop. Otherwise, the iteration will stop.
Syntax for the while loop
while (condition/s)
{
//statement to be executed
}
I provided a simple example below for you to easily understand while loop. Let's say we will display numbers from one (1) to ten (10). You can achieved this by printing the numbers one by one. But what if you'll display 100 or 500 or even a thousand numbers? Are you still gonna print it one by one? The answer is no! It would be cumbersome and will take lots of effort and time while you can achieve it in seconds using a looping statement.
Output while loop
PHP Code while loop
<?php
$i=1;
while($i<=10)
{
echo $i;
$i++;
}
?>
The $i=0 serves as the starting point of our while loop. If the condition holds true, which the value of i is 10 or lesser, then the body of the loop which is to display the value of i and increment will be executed. After the execution, the condition will be tested again and again until the condition becomes false and it will stop.
Hope this helps! Good luck guys! Feel free to leave a comment below if you have questions in mind.
No comments:
Post a Comment