简体   繁体   中英

inner foreach loop check if condition and break only inner loop in php

I have two foreach loop nested, I only want the inner loop to check the condition. If it satisfies or not either one, then terminate the inner loop and come back to the outer loop.

In my condition, the inner loop always needs to run once as I understand my Problem.

Problem: Two arrays. First having all options. Second having only selected. Now math the id. If matched=> Print checked, Else => UnChecked.

I have tried the break; but inner loop only check 1st item then all iteration in else part executed.

@php
foreach($propertyAmenities as $amenity){
   foreach($property->amenities as $new){ 
        if( ($amenity->type == 'amenity') && ($amenity->id == $new->id) ){
        @endphp
        <label class="checkbox-inline control-label">
            <input type="checkbox" name="amenity[]" value="{{$amenity->id}}" {{'checked'}}>{{ $amenity->name }}
        </label>                         
        @php break;                       
          } 
        elseif(($amenity->type == 'amenity')){ @endphp
            <label class="checkbox-inline control-label">
                <input type="checkbox" name="amenity[]" value="{{$amenity->id}}">{{ $amenity->name }}
            </label> 
        @php break;
            }                                                                    
         }
      }
@endphp

First time it checks and print 'checked' next time its only execute ifelse part. i dont know why only first is checked.

all else remain Unchecked.

You can simplify your code by passing the selected options as array in the view.


// Given $selectedOptions = [1, 2, 3, 4...]
@foreach($property->amenities as $amenity)
    <label class="checkbox-inline control-label">
        <input type="checkbox" 
               name="amenity[]" 
               value="{{$amenity->id}}"
               @if (in_array($amenity->id, $selectedOptions))
                   checked="checked"
               @endif
        >{{ $amenity->name }}
    </label>  
@endforeach

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM