Robbè Meulz
Robbè Meulz

Reputation: 49

Laravel 5.2 foreach associative array in key return index

I have this piece oh code:

<?php
    
$levels = array( "0" => "Super User", "1" => "Administrator", "10" => "10", "20" => 20, "30" => "30", "40" => "40", "50" => "50", "99" => "99 News homepage" );

?>

<select name="level" id="modify_modal_level">
    @foreach( $levels as $key => $val )
            <option value="{{ $key }}" <?php echo $selected==$key ? 'selected="selected"': ""?>>{{ $val }}</option>
    @endforeach
</select>

Why the $key inside foreach return the INDEX of array? example:

@foreach( $levels as $key => $val )
   {{ $key }},
@endforeach

prints out: 1,2,3,4,5,6,7,8,

instead of: '0','1','10','20','30','40','50','99'

but the foreach loop in the $key variable MUST return the key value of the associative array, not the key index!

my select results:

<select name="level" id="modify_modal_level">
<option value="1">Super User</option>
<option value="2">Administrator</option>
<option value="3">10</option>
...
<option value="8">99 News homepage</option>
</select>

instead of:

<select name="level" id="modify_modal_level">
<option value="0">Super User</option>
<option value="1">Administrator</option>
<option value="10">10</option>
...
<option value="99">99 News homepage</option>
</select>

Thanks!!

Upvotes: 0

Views: 16791

Answers (1)

camelCase
camelCase

Reputation: 5598

Your code will work as you have it now; are you certain that $levels is correctly generated as you're showing it here?

Controller

$levels = [
    0 => "Super User",
    1 => "Administrator",
    10 => 10,
    20 => 20,
    30 => 30,
    40 => 40,
    50 => 50,
    99 => "99 News homepage",
];

return view('yourview', [
    'levels' => $levels,
    'selected' => '99'
]);

yourview.blade.php

<select name="level" id="modify_modal_level">
    @foreach ($levels as $key => $value)
        <option value="{{ $key }}" @if ($selected == $key) selected @endif>{{ $value }}</option>
    @endforeach
    {{-- $key will be 0, 1, 10, 20, 30, 40, 50, 99 --}}
    {{-- $value will be "Super User", "Administrator", 10, 20, 30, 40, 50, "99 News homepage" --}}
</select>

Note that I also updated to use @if Blade syntax since it's much cleaner and easier to read.

When accessing the view, I get this returned:

enter image description here

Upvotes: 1

Related Questions