Zeeshan DaDa
Zeeshan DaDa

Reputation: 317

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.

Upvotes: 1

Views: 572

Answers (1)

Leonardo Rossi
Leonardo Rossi

Reputation: 3022

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

Upvotes: 1

Related Questions