In PHP, break is used to terminate a loop immediately, and program control resumes at the next statement after the loop.
Example 1: Given an array, the task is to run a loop and display all the values in the array and terminate the loop when 5 is encountered.
Code example:
<?php // PHP break // 声明一个数组并初始化 $array = array( 1, 2, 3, 4, 5, 6, 7 ); //使用foreach循环 foreach ($array as $a) { if ($a == 5) break; else echo $a . " "; } echo "<br>"; echo "循环终止"; ?>
Output:
1 2 3 4 循环终止
Example 2: Given a nested loop, in PHP we can also use break to terminate Two loops. The program below contains a nested loop and terminates it using break statement.
For example, two arrays arr1 and arr2 are given, and the task is to display all the values of arr2 for each value of arr1 until the value of arr1 is not equal to arr2. If the value in arr1 is equal to the value of arr2, use break 2 to terminate both loops and execute other statements.
Code example:
<?php // PHP break // 声明两个数组并初始化 $arr1 = array( 'A', 'B', 'C' ); $arr2 = array( 'C', 'A', 'B', 'D' ); // 使用foreach循环 foreach ($arr1 as $a) { echo "$a "; // 嵌套循环 foreach ($arr2 as $b) { if ($a != $b ) echo "$b "; else break 2; } echo "<br>"; } echo "<br>循环终止"; ?>
Output:
A C 循环终止
This article is an introduction to the use of the break keyword in PHP loops. I hope it will be helpful to friends in need!
The above is the detailed content of How to use break in PHP loop. For more information, please follow other related articles on the PHP Chinese website!