How to use break in PHP loop

藏色散人
Release: 2023-04-04 19:36:02
Original
7158 people have browsed it

In PHP, break is used to terminate a loop immediately, and program control resumes at the next statement after the loop.

How to use break in PHP 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 "循环终止"; 
?>
Copy after login

Output:

1 2 3 4 
循环终止
Copy after login

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( &#39;A&#39;, &#39;B&#39;, &#39;C&#39; ); 
$arr2 = array( &#39;C&#39;, &#39;A&#39;, &#39;B&#39;, &#39;D&#39; ); 
  
// 使用foreach循环
foreach ($arr1 as $a) { 
    echo "$a "; 
      
    // 嵌套循环
    foreach ($arr2 as $b) { 
        if ($a != $b ) 
            echo "$b "; 
        else
            break 2;  
    } 
    echo "<br>"; 
} 
  
echo "<br>循环终止"; 
?>
Copy after login

Output:

A C 
循环终止
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template