PHP - 返回后中断?
我需要在这里使用break还是它会停止循环并只返回一次?
for($i = 0; $i < 5; $i ++) {
if($var[$i] === '') return false;
// break;
}
谢谢你!
do I need to use break here or will it stop looping and just return once?
for($i = 0; $i < 5; $i ++) {
if($var[$i] === '') return false;
// break;
}
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它将只运行一次,停止循环,并退出函数/方法。
但可以说这是一种糟糕的风格。稍后
返回
很容易被忽视,这不利于调试和维护。使用
break
可能会更干净: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
return
later, which is bad for debugging and maintenance.Using
break
might be cleaner:更新:
PHP 7 需要
返回
。不需要break;
,因为循环在return
处结束。当您找到所需的项目时,通常会在 switch 或循环中使用
break;
。示例:
或:
Update:
PHP 7 requires a
return
. Abreak;
is not needed because the loop ends onreturn
.A
break;
is usually used in a switch or loop whenever you have found your needed item.Example:
or:
如果您使用
return
,您的函数(或整个脚本)将返回 - 之后的所有代码都不会被执行。所以回答你的问题:这里不需要break
。但是,如果此处未注释掉break
,则循环将在一次迭代后停止。这是因为您的 if 语句不使用大括号 ({ ... }
),因此它仅覆盖return
语句(换句话说:break 在你的例子中总是被执行)。
If you use
return
, your function (or entire script) will return - all code after that won't be executed. So to answer your question: abreak
is not required here. However, if thebreak
was 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 thereturn
statement (in other words: thebreak
in your example is always executed).