Display comma and space properly in foreach loop

2019-07-18 23:27发布

问题:

I need to display tags on a page and the trick is that I do not want to show comma after the last tag.

So, I have this:

@foreach($tag as $t)
   <a href="/search?q={{$t}}" class="tags">{{$loop->first ? '' : ', '}} {{$t}}</a>
@endforeach

And I want to have this:

A, B, C, D

But instead, I get this:

A , B , C , D

There is extra space between item and comma...

回答1:

You need to check if the loop is on the last item or not, and if not, append a comma and a space (instead of prepending a comma and a space).

For example:

@foreach($tag as $t)
   <a href="/search?q={{$t}}" class="tags">{{$t}}{{$loop->last ? '' : ', '}}</a>
@endforeach

The reason you were getting double spaces is because you were echoing out a space in PHP and also putting a space between your two curly braces.

Update: Although your answer would also work, it's a matter of preference. The original reason you had an extra space between the letter and comma was due to spacing between the curly brace variables.