Break in PHP

“break” statement is using for end the current execution of loop control structure.
Its applicable for for, foreach, while, do-while or switch control structures.

We can add optional parameter with break statement to specify how many control structure should end. By default its value will be 1. Means if we specify break; the it will treat as break 1;

If we specify break 2; it will ends the execution of two control structure .

Look the following structure
while (expression 1)
{
while (expression 2 )
{
break;
}
}
In this structure break statement will ends the execution of while loop with expression 2.

while (expression 1)
{
while (expression 2 )
{
break 2;
}
}
In this structure break statement will ends the execution of two while loop swith expression 1 and expression 2.

See the following sample PHP programs with break statement

<?php
$a = 0;
while ( $a < 3)
{
$a++;
$b = 0;
while ( $b < 5)
{
 $b++;
 if ($b==3)
 {
 break 1;
 }
 echo $a*$b." ";
}
echo "";
}
?>

Its output will be :
1 2
2 4
3 6
( when the value of $b = 3 break statement will ends the execution of while ( $b < 5) )

<?php
$a = 0;
while ( $a < 3)
{
$a++;
$b = 0;
while ( $b < 5)
{
 $b++;
 if ($b==3)
 {
 break 2;
 }
 echo $a*$b." ";
}
echo "";
}
?>

Its output will be :
1 2
( when the value of $b = 3 break statement will ends the execution of two while loops)

break statement is really useful when we want to terminate a loop control structure or a switch case in a particular condition. In some scenarios we need to search for something inside another thing in a loop. we can use break statement when we got the desired result and can eliminate the rest unwanted execution of loops.

Share
Share
Share