<!DOCTYPE html>
<html>
<head>
<title>PHP While Loop</title>
</head>
<body>
<?php
$i=1;
while($i<=5)
{
echo "The number is : " . $i . "<br />";
$i++;
}
?>
</body>
</html>
In the above example $i
hold the value=1
, now check the condition while value of ($i<=5)
. it means execute the code five times. It print the statement line by line.
<!DOCTYPE html>
<html>
<head>
<title>PHP While Loop</title>
</head>
<body>
<?php
$i=1;
$sum=0;
while($i<=27)
{
$sum=$sum+$i;
$i++;
}
echo "Sum= " . $sum;
?>
</body>
</html>
In the above example Variable $i
hold value=1
, initially $sum
hold value=0
. we want to sum of 1 to 27 number using while loop. It execute the statement ($sum=$sum+$i;)
till the condition is true and value is increment by ($i++)
. so it will give the output is 378.
The PHP do...while loop will always execute the block of code once, and then the condition is evaluated, and the statement is repeated as long as the specified condition evaluated to is true.
<!DOCTYPE html>
<html>
<head>
<title>PHP do...while Loop</title>
</head>
<body>
<?php
$i=1;
do
{
echo "The number is : " . $i . "<br />";
$i++;
}while ($i<=5);
?>
</body>
</html>
In the above example variable $i
hold value=1. first execute the statement inside do. After it check while condition ($i<=5)
. So the given statements execute 5 times.
jump statement;
break;
<!DOCTYPE html>
<html>
<head>
<title>PHP Break Statement - inside Loop</title>
</head>
<body>
<?php
for($i=1;$i<=10;$i++){
echo "$i <br />";
if($i==5){
break;
}
}
?>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>PHP Break Statement - inside Loop</title>
</head>
<body>
<?php
for($i=1;$i<=10;$i++){
echo "$i <br />";
if($i==5){
break;
}
}
?>
</body>
</html>