How to use function old() in Blade template to get the last element of array
P粉309989673
2023-09-02 22:00:20
<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>
As mentioned by @apokryfos in the comments:
\Illuminate\Support\Arr::last(old('g3') ?? []) != 3Additional 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>If your
oldvalue isarray, you can usein_arrayinstead.Check if
old('g3')exists, then check ifvalueis in the arrayold('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