How to use break in while loop in php
You can use the keyword break in while statement with the condition
while(loop condition){
if (condition true) {
break;
}
break;
}
}
Lets go with some examples:
Example 1: Say, you want to show numbers 1 to 20 as output like 1, 2, 3, 4, 5, . . . . . . . 17, 18, 19, 20 using while loop
$i = 1;
while( $i <= 20 ) {
echo $i . ", ";
$i = $i + 1;
}
Example 2: Say, you want to show numbers 1 to 20 as output like 1, 2, 3, 4, 5, . . . . . . . 17, 18, 19, 20 using while loop and when number reach to 15, while loop will stop or break
$i = 1;
while( $i <= 20 ) {
echo $i . ", ";
$i = $i + 1;
if($i == 15){
break;
}
}
Example 3: Say, you want to show numbers 1 to 20 as
output like 1, 2, 3, 4, 5, . . . . . . . 17, 18, 19, 20 using do while loop
and when number reach to 15, do while loop will stop or break
$i = 1;
do {
echo $i . ", ";
$i = $i + 1;
if($i == 15){
break;
}
}while( $i <= 20 )Here you can see the difference between while loop and do while loop.
In case of while loop if condition match then only loop start and the program execute the code whereas do while loop for the first time it doesn't have any condition, do the program execute and then it will check the while condition.
How to use break in while loop in php
Reviewed by Ashok Sen
on
09:17:00
Rating:
No comments:
Post a Comment