Display comma and space properly in foreach loop

眉间皱痕 提交于 2019-12-10 17:48:46

问题


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.



来源:https://stackoverflow.com/questions/43612815/display-comma-and-space-properly-in-foreach-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!