I’m trying to make a cart system, which is I need to sum all total product. I’m thinking about saving the total to an array, so I can use array_sum
it later. But somehow the array $total_cart[]
only have last total, for example is if I have three product in my cart, the total saved in the array is only from the third not all product that I have. And the total value is from calculation $price_discount * $cart_item['quantity'];
foreach ($cart_decode as $key => $cart_item): $product = AppModelsProduct::where('id', $cart_item['product_id'])->first(); $discount = ($product->price * $product->discount) / 100; $price_discount = $product->price - $discount; $total_cart = array(); $total_cart[] = $price_discount * $cart_item['quantity']; endforeach
Advertisement
Answer
$total_cart = array();
is in a loop so it reset every time.
You should put $total_cart = array();
before foreach.