laravel007's avatar

How to use comma inside foreach loop?

Hello

I have a list of subjects in an array. I want to print this array in blade file but I want to separate each item of the array by comma. But I don't want the comma end of the last element of the array. Let me know which one is the best approach?

Here is my code-

@foreach(explode(', ', $scholarship->selected_subjects) as $subject)
    <a href="{{ route('subjects.show', $subject) }}">
        {{ $subject }} ,
    </a>
@endforeach
0 likes
3 replies
tisuchi's avatar
tisuchi
Best Answer
Level 70

@laravel007

If your intention is to show comma after each element except the last one, you can easily use $loop->last() inside your foreach. I think it will help to fix your issue.

Check this code-

@foreach(explode(', ', $scholarship->selected_subjects) as $subject)
    <a href="{{ route('subjects.show', $subject) }}">
        {{ $subject }} ,
    </a>

    @if( !$loop->last)
        ,
    @endif
@endforeach

Read more: https://laravel.com/docs/5.8/blade#the-loop-variable

9 likes

Please or to participate in this conversation.