PHP - 返回后中断?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7280716/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 02:23:24  来源:igfitidea点击:

PHP - Break after return?

phpfor-loopreturnbreak

提问by headacheCoder

do I need to use break here or will it stop looping and just return once?

我需要在这里使用 break 还是它会停止循环并返回一次?

for($i = 0; $i < 5; $i ++) {
    if($var[$i] === '') return false;
    // break;
}

Thank you!

谢谢!

采纳答案by Pekka

It will run just once, stop looping, and exit from the function/method.

它将只运行一次,停止循环,并退出函数/方法。

It could be argued though that this is bad style. It is very easy to overlook that returnlater, which is bad for debugging and maintenance.

可以说这是不好的风格。return以后很容易忽略这一点,不利于调试和维护。

Using breakmight be cleaner:

使用break可能更干净:

for($i = 0; $i < 5; $i ++) {
    if($var[$i] === '')
     { set_some_condition; 
       break;
     }
}

if (some_condition)
 return;

回答by Rijk

If you use return, your function (or entire script) will return - all code after that won't be executed. So to answer your question: a breakis not required here. However, if the breakwas not commented out here, the loop would have stopped after one iteration. That's because your if statement doesn't use braces ({ ... }) so it only covers the returnstatement (in other words: the breakin your example is always executed).

如果您使用return,您的函数(或整个脚本)将返回 - 之后的所有代码都不会执行。所以回答你的问题:break这里不需要a 。但是,如果break这里没有注释掉,循环将在一次迭代后停止。那是因为您的 if 语句不使用大括号 ( { ... }),因此它仅涵盖该return语句(换句话说:break您的示例中的the始终被执行)。

回答by Ronnie Oosting

Update:

更新

PHP 7 requires a return. A break;is not needed because the loop ends on return.

PHP 7 需要一个return. break;不需要A ,因为循环结束于return

A break;is usually used in a switch or loop whenever you have found your needed item.

break;当您找到需要的项目时,A通常用于开关或循环中。

Example:

例子:

$items = ['a' , 'b' , 'c']; 

foreach($items as $item) 
{ 
   if($item == 'a') 
   {
       return true; // the foreach will stop once 'a' is found and returns true. 
   }

   return false; // if 'a' is not found, the foreach will return false.
}