Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ftoi's avatar
Level 1

Break Line in @Foreach

Can any méthode to get ouput of this Foreach looking like
U15-U11-U16
not
U15- U11- U16
without spacing \

@foreach ($users as $use)
@if($use->ref)U{{$use->id}}-@endif 
@endforeach 
0 likes
9 replies
Snapey's avatar

put everything on the same line. Line breaks in html are translated to single space

jekinney's avatar

trim('U'.$use->id.'-') or put the whole if statement in the trim.

But @Snapey has a very good point. They need to output all on one line. Otherwise the space will be there.

Ftoi's avatar
Level 1

@Snapey i tried with this before but not working if there is a condition @if
Give me error of
syntax error, unexpected 'if' (T_IF)
working only when we have a simple foreach
@jekinney i use #trim but with no change

MarkLL's avatar

Hi @Ftoi, I had a similar problem with the @if not working when next to other text/output and the only way I solved it was to use php if instead e.g.

@foreach ($users as $use)<?php if ($use->ref) { echo 'U' . $use->id . '-' } ?>@endforeach 

A blade file IS after all just a php script :)

Ftoi's avatar
Level 1

@MarkLL i copy this code but give me error

syntax error, unexpected '<'

but when i breakline between @foreach and <?php if

@foreach ($users as $use)
<?php if ($use->ref) { echo 'U' . $use->id . '-' } ?>
@endforeach 

it's work but still with spacing between U15- U16

MarkLL's avatar

Hi @Ftoi , try putting the whole thing in a block. As others have said, the line break is adding the space. e.g.

<?php
foreach ($users as $use) {
    if ($use->ref) {
        echo 'U' . $use->id . '-';
     }
}
?>

There is definitely issues finding the tokens (@...) in some instances.

1 like
Ftoi's avatar
Level 1

@MarkLL it's work maybe when you do #foreach with '@' it's give a spacing automatically either when you used in block

Please or to participate in this conversation.