How to use function old() in Blade template to get the last element of array
P粉309989673
P粉309989673 2023-09-02 22:00:20
0
2
571
<p>How to get the last element of the array 'g3' inside the old() function without knowing the number of elements. </p> <pre class="brush:php;toolbar:false;"><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></pre> <p>How to get the selected item within a div. </p>
P粉309989673
P粉309989673

reply all(2)
P粉276876663

As mentioned by @apokryfos in the comments:

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

Additional instructions

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

<div>
    @php($data = [1 => "举重", 2 => "慢跑", 3 => "睡觉"])

    <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)["睡觉"], old('g3') ?? []) ? 'none': ''}};"> 不可见</div>
</div>
P粉596191963

If your old value is array, you can use in_array instead.
Check if old('g3') exists, then check if value is in the 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>

How to get the last element of the array, you can try this
array_values() function returns an array containing all the values ​​of the array.
Tip: The returned array will have numeric keys, starting from 0 and increasing gradually.

@if (old('g3'))
   @php
      $size = count(array_values(old('g3')));
      $lastElement = old('g3')[$size - 1];
   @endphp
   // 做一些操作
@endif
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template