5

Here is a quick question: Is there any way to optimise this code with a foreach loop or something like this?

@if(isset($tags[0]))
    <span class="label label-primary">{{ $tags[0] }}</span>
@endif
@if(isset($tags[1]))
    <span class="label label-primary">{{ $tags[1] }}</span>
@endif
@if(isset($tags[2]))
    <span class="label label-primary">{{ $tags[2] }}</span>
@endif
@if(isset($tags[3]))
    <span class="label label-primary">{{ $tags[3] }}</span>
@endif
@if(isset($tags[4]))
    <span class="label label-primary">{{ $tags[4] }}</span>
@endif
@if(isset($tags[5]))
    <span class="label label-primary">{{ $tags[5] }}</span>
@endif
@if(isset($tags[6]))
    <span class="label label-primary">{{ $tags[6] }}</span>
@endif
@if(isset($tags[7]))
    <span class="label label-primary">{{ $tags[7] }}</span>
@endif
@if(isset($tags[8]))
    <span class="label label-primary">{{ $tags[8] }}</span>
@endif
@if(isset($tags[9]))
    <span class="label label-primary">{{ $tags[9] }}</span>
@endif           

Thank you and have a nice day/night !

4 Answers 4

15

You can do it simply like this :

@foreach ($tags as $tag)
    <span class="label label-primary">{{ $tag }}</span>
@endforeach
Sign up to request clarification or add additional context in comments.

1 Comment

Shouldn't {{ $tags }} be {{ $tag }}? (Without the s)
5

You can use an @foreach loop (as suggested by other answers) or an @for loop. Use blade syntax for control structures (preceeded by an @ symbol)

@for($i = 0; $i <= 9; $i++)
@if(isset($tags[$i]))
<span class="label label-primary">{{ $tags[$i] }}</span>
@endif
@endfor

8 Comments

Thank you! I think I finally understood how for loop works !
No problem. And just so you're aware, a "thank you" comment is always nice, but should be avoided in favour of an action that actually closes the question. All of the answers posted here are valid; so consider upvoting them and marking one as an answer.
Haha, no, you upvoted my comment :P And I said upvote "them", not just mine.
Why, given an indexed array, would you need to range over 9 indices? @foreach will range over each of the elements in the $tags array.
@TimLewis That wording is much better, thank you. :)
|
4

Per the documentation, you can do @for loops.

@for ($i = 0; $i < 10; $i++)
    @if(isset($tags[$i]))
         <span class="label label-primary">{{ $tags[$i] }}</span>
    @endif
@endfor

Comments

0
@foreach ($tags as $data) 
<span class="label label-primary">{{$data->property }}</span> 
@endforeach

you can also use the for else in blade just see the laravel docs https://laravel.com/docs/5.5/blade

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.