PHP 중단

WBOY
풀어 주다: 2024-08-29 12:40:45
원래의
933명이 탐색했습니다.

PHP break 문은 for 루프, while 루프, do-while, 스위치 및 for-each 루프와 같은 조건문에서 돌아올 때까지 기다리지 않고 즉시 루프를 종료하는 데 사용됩니다. 여러 개의 루프가 있고 break 문을 사용하면 첫 번째 내부 루프에서만 종료됩니다. Break는 명령문 블록 내부에 존재하며 필요할 때마다 사용자가 루프에서 벗어날 수 있는 완전한 자유를 제공합니다.

광고 이 카테고리에서 인기 있는 강좌 재무 모델링 및 가치 평가 - 전문 분야 | 51 코스 시리즈 | 모의고사 30개

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

구문:

<?php
//variable declarations
//conditional statement block
{
break;
}
?>
로그인 후 복사

순서도:

PHP 중단

위와 같이 코드는 루프의 조건이 만족되면 먼저 조건문 블록에 들어가고 조건이 만족되지 않을 때까지 루프의 명령문을 계속 실행합니다. 코드에 break 문이 작성되면 프로그램이 이를 발견하자마자 표시된 대로 조건 만족 여부에 관계없이 코드가 현재 루프에서 종료됩니다.

PHP의 Break 예시

다양한 시나리오에서 각 조건문에 대한 몇 가지 예를 살펴보고 동일한 동작을 확인하여 break 문의 작동을 이해해 보겠습니다.

예시 #1

“for” 루프 내부의 Break 문.

코드:

<?php
$var = 1;
for ($var = 0;$var <= 10;$var++)
{
if ($var==5)
{
break;
}
echo $var;
echo "\n";
}
echo "For loop ends here" ;
?>
로그인 후 복사

출력:

PHP 중단

여기에서는 1을 변수 “var”로 초기화하여 for 루프에서 1부터 10까지의 숫자를 인쇄합니다. "var"는 if 루프 조건을 만날 때까지 1부터 시작하여 증분 숫자를 인쇄하기 시작합니다. 여기서 우리는 변수의 값이 5에 도달하면 변수가 루프에서 나와야 한다고 언급하고 있습니다. 이는 표시된 대로 break 문을 사용하여 수행됩니다. break 문이 실행되고 for 루프 조건이 만족되지 않더라도 for 루프에서 빠져나오면 "For 루프는 여기에서 끝납니다"를 인쇄하는 것처럼 출력에서 ​​동일한 것을 볼 수 있습니다. 따라서 break 문은 다른 모든 반복의 전체 논리에서 나옵니다.

예시 #2

while 루프에서 break 문의 기능을 확인하는 예제입니다.

코드:

<?php
$var = 0;
while( $var < 10) {
$var++;
if( $var == 5 )break;
echo ("Current variable value = $var");
echo "\n";
}
echo ("Exited loop at variable value = $var" );
?>
로그인 후 복사

출력:

PHP 중단

위 프로그램 변수 "var"는 먼저 0으로 초기화되고 while 루프를 사용하여 해당 값을 1씩 증가시키고 동일한 내용을 인쇄합니다. 변수 값이 5가 되면 break 문을 사용하여 코드가 종료되도록 하는 if 조건을 작성하고 있습니다. 이 break는 값이 10이 될 때까지 변수를 증가시키는 지정된 조건이 아니더라도 현재 while 루프에서 종료되도록 합니다. 만났다. 루프가 끊어지는 변수값을 표시하고 있습니다.

예시 #3

여기에서는 foreach 루프에 break 문을 구현합니다.

코드:

<?php
$array = array('A', 'B', 'C', 'D', 'E', 'F');
foreach ($array as $let) {
if ($let == 'E') {
break;
}
echo "$let \n";
}
로그인 후 복사

출력:

PHP 중단

이 프로그램에서는 먼저 문자 모음을 포함하는 배열을 선언합니다. 그런 다음 foreach 루프를 사용하여 배열의 모든 요소를 ​​하나씩 인쇄합니다. 배열 포인터의 값이 문자 "E"에 도달하면 루프를 중단하기 위해 조건문이 도입됩니다. 따라서 break 문을 만나면 배열의 다음 문자(예: "F")를 인쇄하지 않고 코드가 종료됩니다.

예시 #4

break의 가장 일반적인 적용은 아래에 표시된 스위치 문에 있습니다.

코드:

<?php
$a=1;
switch ($a) {
case 0:
echo "a equals 0";
break;
case 1:
echo "a equals 1";
break;
case 2:
echo "a equals 2";
break;
}
?>
로그인 후 복사

출력:

PHP 중단

처음에는 변수 값을 1로 초기화하는 간단한 스위치 문의 예입니다. 그런 다음 스위치 조건을 이용하여 변수값을 확인하고 조건이 일치하면 출력해 줍니다.

예시 #5

두 개 이상의 루프(조건문)가 있을 때 break 문의 작업을 살펴보겠습니다.

코드:

<?php
// PHP program to verify break of inner loop
// Declaration of 2 arrays as below
$array1 = array( 'One', 'Two', 'Three' );
$array2 = array( 'Three', 'One', 'Two', 'Four' );
// Outer foreach loop
foreach ($array1 as $a1) {
echo "$a1 ";
// Inner nested foreach loop
foreach ($array2 as $a2) {
if ($a1 != $a2 )
echo "$a2 ";
else
break 2;
}
echo "\n";
}
echo "\n Loop Terminated";
?>
로그인 후 복사

출력:

PHP 중단

Here we are using 2 nested foreach loops and also showing a case of using “break 2” which breaks out of both the loops in contrast to the “break” statement which breaks out of only the inner loop.

We have declared two arrays array1 and array2 and we are displaying the values of array2 for each value of array1 until and unless the value of array1 is not equal to array2. Once the value in array1 becomes the same as array2 we are breaking both loops by making use of break 2 statement which prevents the code from executing any more statements.

Example #6

Here we shall see how to use break statements to come out of “n” number of loops (conditional statements).

Code:

<?php
## Outermost first for loop
for($a=1;$a<5;$a++){
echo ("Value of a is = $a");
echo "\n";
## Second for loop
for($b=1;$b<3;$b++){
echo ("Value of b is = $b");
echo "\n";
## Third for loop
for($c=2;$c<3;$c++){
echo ("Value of c is = $c");
echo "\n";
## Fourth for loop
for($d=2;$d<4;$d++){
echo ("Value of d is = $d");
echo "\n";
if( $a == 3 ){
break 4;
}
}
}
}
}
echo 'Loop has terminated and value of a = '.$a;
?>
로그인 후 복사

Output:

PHP 중단

The break statement followed by the number of loops that need to be exited from are used to terminate from “n” number of loops.

Syntax:

break n;
로그인 후 복사

where n is the number of loops that need to be exited from the loop.

We are using 4 nested for loops for this purpose. Variables a, b, c, d is initialized respectively for each for loop and we are incrementing their values by 1. The same values are displayed in the output to understand its flow better. At last, we are giving a condition for all the 4 loops to break if the value of the first variable becomes equal to 3 which it eventually did and can be shown in the output. We are printing the loop has terminated at the end along with as value to note the break’s functionality.

Conclusion

When we are using one or more conditional statements in our code and we need to exit from the same at a particular point, we can use the break statement. Basically, it helps to terminate from the code when the condition we give falls TRUE. We can also pass an integer along with break to terminate from any number of existing loops instead of declaring the break again and again.

위 내용은 PHP 중단의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
php
원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!