Antonio Morales Antonio Morales - 1 year ago 131
PHP Question

Capture the value of previous iteration in a loop Laravel PHP

I have a foreach iteration with this variable:

$cart = Cart {#167 ▼

+lines: array:2 [▼
0 => CartLine {#168 ▼
+cart_line_id: 989642
+cart_id: 13049301
+parent_line_id: null
+quantity: 1
+article_id: 1164
+article_name: "CUSTOMIZED T-SHIRT"
+pvp: 29.5
}
1 => CartLine {#170 ▼
+cart_line_id: 989643
+cart_id: 13049301
+parent_line_id: 989642
+quantity: 2
+article_id: 199
+article_name: "EXTRA COMPLEMENT"
+pvp: 2.5

}
]

}


And this is my laravel foreach loop:

@foreach ($cart->lines as $line)

@endforeach


I want this:

@foreach ($cart->lines as $line)
@if($line->parent_line_id == $line->cart_line_id(previous))
//print extra
@endif
@endforeach


I want get the previous item of the current item iteration.

This is possible?

Answer Source

Like this:

@foreach ($cart->lines as $index => $line)
   @if($index > 0 && $line->parent_line_id == $cart->lines[$index - 1]->cart_line_id)
     //print extra
   @endif
@endforeach

Or using $loop variable (seeing you're using 5.3):

@foreach ($cart->lines as $line)
   @if(!$loop->first && $line->parent_line_id == $cart->lines[$loop->index - 1]->cart_line_id)
     //print extra
   @endif
@endforeach
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download