Last element of an array with function old() in blade

Viewed 48

How do I get the last element of an array 'g3' inside old() without knowing the number of elements.

      <select name="g3[]" multiple="multiple">
        <option value="1" @if (old('g3')=="1" ) {{ 'selected' }} @endif >lifting</option>
        <option value="2" @if (old('g3')=="2" ) {{ 'selected' }} @endif >jogging</option>
        <option value="3" @if (old('g3')=="3" ) {{ 'selected' }} @endif >sleeping</option>  
      </select>

      <div  {!!  old('g3')  != 3 ? '':' style="display: none"' !!}> Not to be seen</div>

How do I get the item selected inside div.

2 Answers

As mentioned by @apokryfos in a comment:

Could use Arr::last

\Illuminate\Support\Arr::last(old('g3') ?? []) != 3

Addendum

Based on your comment, the demo below should be sufficient:

that works,I have just edited my qn, how to get an item without knowing if it's was first,second or last when selected. inside div.Thanks and sorry for my English

<div>
    @php($data = [1 => "lifting", 2 => "jogging", 3 => "sleeping"])

    <select name="g3[]" id="g3" multiple>
        @foreach($data as $id => $v)
            <option value="{{$id}}" {{in_array($id, old('g3') ?? []) ? 'selected' : ''}}>
                {{$v}}
            </option>
        @endforeach
    </select>

    <div style="display: {{!in_array(array_flip($data)["sleeping"], old('g3') ?? []) ? 'none': ''}};"> Not to be seen</div>
</div>

If your old value is array, you can use in_array instead.
Check old('g3') exists and then check value is in array old('g3')

<select name="g3[]" multiple="multiple">
   <option value="1" @if (old('g3') && in_array('1', old('g3')) selected @endif >lifting</option>
   <option value="2" @if (old('g3') && in_array('2', old('g3')) selected @endif >jogging</option>
   <option value="3" @if (old('g3') && in_array('3', old('g3')) selected @endif >sleeping</option>  
</select>

And how to get last element of array, you can try this
The array_values() function returns an array containing all the values of an array.
Tip: The returned array will have numeric keys, starting at 0 and increase by 1.

@if (old('g3'))
   @php
      $size = count(array_values(old('g3')));
      $lastElement = old('g3')[$size - 1];
   @endphp
   // Do something
@endif
Related