A while loop is used to repeatedly execute a set of statements as long as the condition remains true.

Syntax

while(condition)
{
//do this
}

Learn about the difference between for loop and while loop.

Example

<?php
$i=1;
while(i<5)
{
echo $i."<br>";
$i++;
}
?>

Ouput

1
2
3
4

Using break keyword

You can use the break keyword to stop the execution of a while loop.

<?php
$a=0;
while ($a <= 10)
{
echo $a."<br>";
if ($a==3)
{
break;
}
$a++;
}
?>

Output

0
1
2
3

Alternate syntax of PHP while loop

You can also use the following alternate syntax to create a while loop.

<?php
$a=0;
while($a<3):
echo $a."<br>";
$a++;
endwhile;
?>