PHP While Loop We have already discussed the PHP For Loop. Now we are discussing about another loop.
In PHP, we have the following looping statements:
PHP While Loop
The while loop executes a block of code as long as the specified condition is true.
Syntax
while (condition) {
block of code;
}
Example
<?php
$i = 0;
while ($i < 5)
{
echo "<br> value of i is " . $i;
$i++;
}
?>
Output
value of i is 0
value of i is 1
value of i is 2
value of i is 3
value of i is 4
At the end of each execution, while condition is checked again. If the condition has a true value, the block of code will be executed again. If condition has a false value, the loop was broken.
Do While loop
The do while is same as the while loop but main difference is the block of code will be executed at least once before the condition is checked for a true or false value then repeats the loop as long as the specified condition is true.
Syntax
do {
block of code;
} while (condition);
Example
<?php
$i = 0;
do
{
echo β<br> value of i isβ . $i;
$i++;
} while ($i < 5);
?>
Output
value of i is 0
value of i is 1
value of i is 2
value of i is 3
value of i is 4
Infinite While loop
It is an infinite loop which will execute the block of code till a break statement is applied explicitly. Therefore while(1), while(true) or while(-130) all will give infinite loop only.
Use of Infinite while loop is in the Client-Server program. In the program, the server runs in an infinite while loop to receive the packets sent form the clients.
Syntax
while (1) or while (true) or while (any non-zero integer) {
block of code;
}
Example
<?php
while (1)
{
echo "<br> developer helps";
}
?>
Output
developer helps
developer helps
developer helps
developer helps
developer helps
developer helps
developer helps
developer helps...... infinity times
While (0) or While (false) loop
Condition will always be false in this case so block of code will never get executed.
Syntax
while (0) or while (false){
block of code;
}
Example
<?php
while (0)
{
echo "<br> developer helps";
}
echo "while loop not execute";
?>
Output
while loop not execute
More Related Post
Thanks for the reading post. I hope you like and understand the post. If you have any doubt regarding this post please comment below.