search

Home  >  Q&A  >  body text

How to use function old() in Blade template to get the last element of array

<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粉309989673P粉309989673524 days ago612

reply all(2)I'll reply

  • P粉276876663

    P粉2768766632023-09-03 17:53:34

    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>
    

    reply
    0
  • P粉596191963

    P粉5961919632023-09-03 12:59:05

    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

    reply
    0
  • Cancelreply