dtvfshi5248 2017-11-22 05:40
浏览 37
已采纳

Laravel,是否有可能打破foreach内部的陈述?

I need to break if statement inside foreach once the the if condition is true. Is it possible to break the if statement without breaking the foreach?

Below shows the codes that I was currently using now. But if I do this, it break the foreach too.

Codes

@foreach($furniture as $fur)
{
  //do something
  @if($fur->broken == true)
    //do something
    <php break; ?>
  @endif
}
@endforeach
  • 写回答

4条回答 默认 最新

  • duana1986 2017-11-22 06:07
    关注

    I would use a do while inside the foreach

    foreach($furniture as $fur){
    //do something
        do{
            if($fur->broken == true){
              //do something
               break;
            }
        }while(false);
    }
    

    The Do While evaluates the condition after the first iteration, in this case the loop ends after the first iteration (because the condition is false), but this gives us a structure we can break out of.

    The other way to do this is to use a switch statement with an if in it.

    foreach($furniture as $fur){
    //do something
        switch(1){
            default:
               if($fur->broken == true){
                //do something
                 break;
               }
        }
    }
    

    Also note to break out of the foreach you can do break 2 instead of just break.

    All that said, I would say just from a best practice standpoint this makes the code less readable and what you need could be done without it ( most likely ) but I would need more details to help with that.

    UPDATE

    IS this a template thing like ( Blade )? It's not clear in the question. I don't use blade, but I've seen it, studied it some, so that makes sense with the @ sign. But as I took the time to type this I'll leave it here.

    Of note the same could probably be done in blade by faking a loop ( loop 1 time ) inside the foreach, same principle as the do while. Assuming it supports break levels. Something like this

     @foreach($furniture as $fur)
        //do something 
         @foreach($fake as $f)     
             @if($fur->broken == true)           
              //do something
                 @break
             @endif
         @endforeach
      //do something else
    @endforeach
     //where fake is like  $fake = [1];  single element, so one loop.
    

    You could also do the extra loop inside or outside the if block, as your needs dictate.

    I am also not sure if Blade supports switch most template engines don't, but it may be cleaner to use if it does.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度