Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

130
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda