PHP break (Single and Nested Loops)
In PHP break is used to immediately terminate the loop and the program control resumes at the next statement following the loop.
Method 1: Given an array the task is to run a loop and display all the values in array and terminate the loop when encounter 5.
Examples:
Input : array1 = array( 1, 2, 3, 4, 5, 6, 7 )
Output : 1 2 3 4
Loop Terminated
The loop contains an if condition and when condition is true then
loop will break otherwise display the array content.
Input : array1 = array( '10', '2', '5', '20', '40' )
Output : 10 2
Loop Terminated
Program:
<?php
$array = array ( 1, 2, 3, 4, 5, 6, 7 );
foreach ( $array as $a ) {
if ( $a == 5)
break ;
else
echo $a . " " ;
}
echo "\n" ;
echo "Loop Terminated" ;
?>
|
Output:
1 2 3 4
Loop Terminated
Method 2: Given nested loops, in PHP we can use break 2 to terminate two loops as well. Below program contains the nested loop and terminate it using break statement.
For example given two array arr1 and arr2, and the task is to display all the value of arr2 for every value of arr1 till the value of arr1 not equal to arr2. If the value in arr1 is equal to the value of arr2 then terminate both the loops using break 2 and execute the further statements.
Examples:
Input : arr1 = array( 'A', 'B', 'C' );
arr2 = array( 'C', 'A', 'B', 'D' );
Output : A C
Loop Terminated
Input : arr1 = array( 10, 2, 5, 20, 40 )
arr2 = array( 1, 2 )
Output :10 1 2
2 1
Loop Terminated
<?php
$arr1 = array ( 'A' , 'B' , 'C' );
$arr2 = array ( 'C' , 'A' , 'B' , 'D' );
foreach ( $arr1 as $a ) {
echo "$a " ;
foreach ( $arr2 as $b ) {
if ( $a != $b )
echo "$b " ;
else
break 2;
}
echo "\n" ;
}
echo "\nLoop Terminated" ;
?>
|
Output:
A C
Loop Terminated
Last Updated :
20 Nov, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...