Bird
0
0

You want to display a list of products only if there are any products in the array. Which Blade code correctly does this?

hard📝 state output Q15 of 15
Laravel - Views and Blade Templates
You want to display a list of products only if there are any products in the array. Which Blade code correctly does this?
A@if(count($products) > 0) @foreach($products as $product) {{ $product->name }} @endforeach @endif
B@foreach($products as $product) @if($products) {{ $product->name }} @endif @endforeach
C@for($i = 0; $i < count($products); $i++) @if($products[$i]) {{ $products[$i]->name }} @endif @endfor
D@if($products) @foreach($products as $product) {{ $product->name }} @endforeach @endif
Step-by-Step Solution
Solution:
  1. Step 1: Check condition to display list

    @if(count($products) > 0) @foreach($products as $product) {{ $product->name }} @endforeach @endif uses @if(count($products) > 0) which correctly and explicitly checks if products exist before looping.
  2. Step 2: Analyze other options

    B places the check inside the loop, which is redundant since @foreach skips empty arrays. C uses manual @for with array indexing, which is error-prone (e.g., for associative arrays) and less idiomatic than @foreach. D uses @if($products), which works via implicit boolean conversion (empty arrays are falsy) but is less explicit and readable than count > 0.
  3. Final Answer:

    @if(count($products) > 0) followed by @foreach -> Option A
  4. Quick Check:

    Check count > 0 before @foreach [OK]
Quick Trick: Use count() > 0 to check non-empty arrays before loops [OK]
Common Mistakes:
  • Using implicit @if($products) instead of explicit count > 0
  • Placing condition inside loop unnecessarily
  • Using @for with inner @if redundantly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Laravel Quizzes