Catto
Catto

Reputation: 527

array_push replacing value instead of adding new value in array

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

Upvotes: 1

Views: 77

Answers (2)

Lee
Lee

Reputation: 418

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

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

Upvotes: 3

Muhammad Dyas Yaskur
Muhammad Dyas Yaskur

Reputation: 8118

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

Upvotes: 3

Related Questions