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.
CodePudding user response:
As mentioned by @apokryfos in a comment:
Could use Arr::last
\Illuminate\Support\Arr::last(old('g3') ?? []) != 3
CodePudding user response:
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
@if (old('g3'))
@php
$size = count(old('g3'));
$lastElement = old('g3')[$size - 1];
@endphp
// Do something
@endif