WEB언어/PHP
[PHP] break / return / exit 차이점
saltdoll
2019. 7. 31. 05:56
반응형
$arr = array('one', 'two', 'three', 'four', 'stop', 'five');
foreach ($arr as $val) {
if ($val == 'stop') {
break; /* You could also write 'break 1;' here. */
}
echo "$val<br />\n";
}
break = 루프 탈출
- for, foreach, while 등 여러 번 반복되는 루프의 경우에 해당됨
- 루프 이후에 등장하는 코드를 계속 실행함
- if문은 반복문이 아니라 조건 충족시 1번만 실행되는 코드이므로 해당없음
return = 함수 탈출 또는 인클루드 탈출
- 함수 안에서 쓰면 함수 실행을 종료하고, 그 함수를 호출했던 지점으로 돌아가서 계속 실행함
- 함수 밖에서 쓰면 현재 파일을 인클루드했던 파일로 돌아가서 계속 실행함
- 함수 밖인데 인클루드한 것도 없으면 그냥 종료됨, 즉 exit과 동일한 효과가 됨
exit, die = 무조건 종료
- 말 그대로 프로그램이 죽어버림
출처: https://www.phpschool.com/gnuboard4/bbs/board.php?bo_table=qna_function&wr_id=415205
예제
for($i = 1;;$i++){
if($i > 10){
break; // 루프를 빠져나감
}
echo $i;
}
break
(PHP 4, PHP 5, PHP 7)
break ends execution of the current for, foreach, while, do-while or switch structure.
예제 2
$arr = array('one', 'two', 'three', 'four', 'stop', 'five');
foreach ($arr as $val) {
if ($val == 'stop') {
break; /* You could also write 'break 1;' here. */
}
echo "$val<br />\n";
}
Changelog for break
VERSION | DESCRIPTION |
7.0.0 | break outside of a loop or switch control structure is now detected at compile-time instead of run-time as before, and triggers an E_COMPILE_ERROR. |
5.4.0 | break 0; is no longer valid. In previous versions it was interpreted the same as break 1;. |
5.4.0 | Removed the ability to pass in variables (e.g., $num = 2; break $num;) as the numerical argument. |
예제 3
foreach($equipxml as $equip) {
$current_device = $equip->xpath("name");
if ( $current_device[0] == $device ) {
// found a match in the file
$nodeid = $equip->id;
// will leave the foreach loop and also the if statement
break;
}
this_command_is_not_executed_after_a_match_is_found();
}
예제 4
foreach (array('1','2','3') as $a) {
echo "$a ";
foreach (array('3','2','1') as $b) {
echo "$b ";
if ($a == $b) {
break 2; // this will break both foreach loops
}
}
echo ". "; // never reached
}
echo "!";
Resulting output:
1 3 2 1 !
참고: https://stackoverflow.com/questions/9215588/break-out-of-if-and-foreach
반응형