Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 250
Zachary Dale Avatar asked Nov 18 '16 09:11

Zachary Dale


5 Answers

The selected answer is too complicated. Laravel has a simpler solution:

{{ $items->pluck('tag')->implode(', ') }}
like image 191
Zentag Avatar answered Nov 03 '22 17:11

Zentag


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
like image 40
Alexey Mezenin Avatar answered Nov 03 '22 16:11

Alexey Mezenin


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
like image 26
Biswa Avatar answered Nov 03 '22 17:11

Biswa


Use implode:

{{ implode(', ', $tags) }}
like image 39
Mihai Matei Avatar answered Nov 03 '22 17:11

Mihai Matei


implode is one option or you can using join as well like this

{{ join(', ', $tags) }} 

Try the first one or this one.. good luck

like image 1
anuraj Avatar answered Nov 03 '22 15:11

anuraj