19

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.

1

7 Answers 7

63

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

{{ $items->pluck('tag')->implode(', ') }}
Sign up to request clarification or add additional context in comments.

1 Comment

How would wrap each element in anchor tag? And ideally, display "..." when a list is "too long"?
30

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

If there is only one element in array comma won't appear right ?
@ZacharyDale yes, you're right, you'll not see comma in this case.
7

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

Comments

5

Use implode:

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

1 Comment

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(', ') }}
1

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

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

Try the first one or this one.. good luck

Comments

1

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

Comments

0

Try implode():

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

// output

one,two,three

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.