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.

5 Answers 11

Use implode:

{{ implode(', ', $tags) }}
1 upvote
  flag
In Laravel you often deal with Collection objects instead of raw PHP arrays. In those cases, Collection provides an implode method itself. Use it like {{ $user->sports->pluck('name')->implode(', ') }} – Thijs

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

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

Try the first one or this one.. good luck

Try implode():

$arr = ['one', 'two', 'three'];
echo implode(',', $arr);

// output

one,two,three
up vote 5 down vote accepted

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
upvote
  flag
If there is only one element in array comma won't appear right ? – Zachary Dale
upvote
  flag
@ZacharyDale yes, you're right, you'll not see comma in this case. – Alexey Mezenin

I believe what you are looking for might be something like this: //have your array in php tags //$arr = ['one', 'two', 'three']; ? > //go through the array with foreach and if the count of the array is not equal to the las element then put coma after it

@foreach ($arr as $key => $value)
    @if( count( $arr ) != $key + 1 )
        {{ $value }},
     @else
        {{ $value }}
    @endif
@endforeach

Not the answer you're looking for? Browse other questions tagged or ask your own question.