Skip to content
Advertisement

Detect if array contains another array

I’m using external API for my website. When user select city and town, API returns neighborhoods. But the problem is, if there is only one neighborhood array contains name and neighborhood id. But if there is more than one, it contains multiple array for each neighborhood.

Single example ;

array(
'Code' => 123,
'NeighborhoodName' => 'Name'
)

enter image description here

Multiple Example

array(
    array(
    'Code' => 123,
    'NeighborhoodName' => 'Name'
    ),
array(
    'Code' => 123,
    'NeighborhoodName' => 'Name'
    )

) enter image description here

I have to show data to user inside select box.

<select  id="nh" class="form-control" name="belde" wire:model='selectedNH'>
            <option value="" selected default></option>
            
                @foreach($nh as $nhArray)
                     <option value="{{$nhArray['Kod']}}">{{$koyArray['KOY_Adi']}}</option>
                 @endforeach
            @endif
        </select>

As expected, if there is only one neighborhood, my code throws Illegal string offset ‘Kod’ error. I tried to gettype for compare array childs but didnt work

Advertisement

Answer

Try this:

@if(isset($nh['Kod']))
    <option value="{{ $nh['Kod'] }}">{{ $nh['KOY_Adi'] }}</option>
@else
    @foreach($nh as $nhArray)
        <option value="{{$nhArray['Kod']}}">{{$koyArray['KOY_Adi']}}</option>
    @endforeach
@endif

Some explanations for the answer: in the if statement, you check the array key [‘Kod’], if the array key exists, then you know this all the places are not displayed in the array, and then in the else statement, you do what you did before, to loop through the array.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement