PHP - 返回后中断?

发布于 2024-12-02 12:08:27 字数 160 浏览 0 评论 0原文

我需要在这里使用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技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

眉目亦如画i 2024-12-09 12:08:27

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

但可以说这是一种糟糕的风格。稍后返回很容易被忽视,这不利于调试和维护。

使用 break 可能会更干净:

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

if (some_condition)
 return;

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:

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

if (some_condition)
 return;
可爱暴击 2024-12-09 12:08:27

更新

PHP 7 需要返回。不需要 break;,因为循环在 return 处结束。

当您找到所需的项目时,通常会在 switch 或循环中使用 break;

示例:

$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.
}

或:

$items = ['a' , 'b' , 'c']; 
    
foreach($items as $item)
{
    return $item == 'a'; // if 'a' is found, true is returned. Otherwise false.
}

Update:

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

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

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.
}

or:

$items = ['a' , 'b' , 'c']; 
    
foreach($items as $item)
{
    return $item == 'a'; // if 'a' is found, true is returned. Otherwise false.
}
所谓喜欢 2024-12-09 12:08:27

如果您使用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: a break is not required here. However, if the break 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 the return statement (in other words: the break in your example is always executed).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文