在foreach循环中正确显示逗号和空格 [英] Display comma and space properly in foreach loop

查看:363
本文介绍了在foreach循环中正确显示逗号和空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在页面上显示标签,诀窍是我不想在最后一个标签后显示逗号.

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

所以,我有这个:

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

我想要这个:

A, B, C, D

但是,相反,我得到了:

But instead, I get this:

A , B , C , D

项目和逗号之间有多余的空间...

There is extra space between item and comma...

推荐答案

您需要检查循环是否在最后一项上,否则,请添加逗号和空格(而不是在逗号和空间).

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).

例如:

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

获得双倍空格的原因是因为您在PHP中回显了一个空格,并且还在两个花括号之间放置了一个空格.

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.

这篇关于在foreach循环中正确显示逗号和空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆