Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

122
Views
Display comma and space properly in foreach loop

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

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!