I am displaying elements of an array @foreach($tags as $tag)$tag->@endforeach
. The output is tag1tag2tag3
. What is the possible way to sho elements of array in tag1,tag2,tag3
. And how to not show,
if there is only one element in array.
The selected answer is too complicated. Laravel has a simpler solution:
{{ $items->pluck('tag')->implode(', ') }}
implode()
is good for echoing simple data. In real project you usually want to add some HTML or logic into the loop, use $loop
variable which is available since 5.3:
@foreach ($arrayOrCollection as $value)
{{ $loop->first ? '' : ', ' }}
<span class="nice">{{ $value->first_name }}</span>
@endforeach
Use this. We can implement it using $loop->last
@foreach ($arrayOrCollection as $value)
<span class="nice">
{{ $value->first_name }}
@if( !$loop->last)
,
@endif
</span>
@endforeach
Use implode:
{{ implode(', ', $tags) }}
implode is one option or you can using join as well like this
{{ join(', ', $tags) }}
Try the first one or this one.. good luck
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With