Home > Net >  array_push replacing value instead of adding new value in array
array_push replacing value instead of adding new value in array

Time:12-13

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

CodePudding user response:

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

CodePudding user response:

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

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

  • Related