The break statement
The break statement is situated inside the statement block. It gives you full control and whenever you want to exit from the loop you can come out. After coming out of a loop immediate statement to the loop will be executed.
jump statement;
break;
Let's see a simple example to break the execution of for loop if value of i is equal to 6.
<?php
for($i=1;$i<=10;$i++){
echo "$i <br/>";
if($i==6){
break;
}
}
?>
Output
1
2
3
4
5
6
The PHP break statement breaks the execution of inner loop only.
<?php
for($i=1;$i<=3;$i++){
for($j=1;$j<=3;$j++){
echo "$i $j<br/>";
if($i==2 && $j==2){
break;
}
}
}
?>
Output:
1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3
The PHP break statement breaks the flow of switch case also.
<?php
$color="Red";
switch($color){
case "Black":
echo("Color Is Black");
break;
case "Blue":
echo("Color Is Blue");
break;
case "Red":
echo("Color Is Red");
break;
default:
echo("Color Is Not Blue, Black, Yellow");
}
?>
Output:
Color Is Red
© 2024 Easy To Learning. All Rights Reserved | Design by Easy To Learning