Home > Mobile >  array_sum return 0. How do I sum my array?
array_sum return 0. How do I sum my array?

Time:10-14

I have this

        foreach ($item_id as $key => $no) {
            $input['price'] = $price[$key]['price'];
            $input['quantity'] = $quantity[$key];
            $subtotal[] = [$input['price']*$input['quantity']];
        }
        $total_price = array_sum($subtotal);

When I dd($total_price) it return 0.

When I dd($subtotal) it return my array like this

array:3 [▼
  0 => array:1 [▼
    0 => 3000000
  ]
  1 => array:1 [▼
    0 => 3
  ]
  2 => array:1 [▼
    0 => 9
  ]
]

How do I sum my array from that? Thanks!

CodePudding user response:

In this line :

$subtotal[] = [$input['price']*$input['quantity']];

you are assigning an array, which is why you end up with the structure that you see when you dd($subtotal).

Just do :

$subtotal[] = $input['price']*$input['quantity'];

and you should be fine.

  • Related