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.
-
1Check implode - php.net/manual/en/function.implode.phpjitendrapurohit– jitendrapurohit2016-11-18 09:53:29 +00:00Commented Nov 18, 2016 at 9:53
Add a comment
|
7 Answers
The selected answer is too complicated. Laravel has a simpler solution:
{{ $items->pluck('tag')->implode(', ') }}
1 Comment
Salvis Blūzma
How would wrap each element in anchor tag? And ideally, display "..." when a list is "too long"?
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
2 Comments
Zachary Dale
If there is only one element in array comma won't appear right ?
Alexey Mezenin
@ZacharyDale yes, you're right, you'll not see comma in this case.
Use implode:
{{ implode(', ', $tags) }}
1 Comment
Thijs
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(', ') }}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