Zachary Dale Zachary Dale - 21 days ago 6
PHP Question

Create comma separated list from array in laravel/blade?

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.

Answer

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