1

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 = \App\Models\Product::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
2
  • 1
    It's because you reset the array on every iteration. Move $total_cart = array(); outside the foreach loop Commented Dec 13, 2021 at 2:23
  • @marco-a ah! thank you Commented Dec 13, 2021 at 2:28

2 Answers 2

3

$total_cart = array(); is in a loop so it reset every time.

You should put $total_cart = array(); before foreach.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your help, now it's working correctly
3

Your code creates/defines a new array in every single loop. You should define $total_cart before the looping/foreach.

$total_cart = array();
    foreach ($cart_decode as $key => $cart_item):
        $product = \App\Models\Product::where('id', $cart_item['product_id'])->first();
        $discount = ($product->price * $product->discount) / 100;
        $price_discount = $product->price - $discount;
    
        $total_cart[] = $price_discount * $cart_item['quantity'];
    endforeach

1 Comment

Thanks for your help, now it's working correctly

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.