array:3 [▼
0 => array:3 [▼
"product_id" => "5"
"quantity" => "1"
"price" => "250"
]
1 => array:3 [▼
"product_id" => "6"
"quantity" => "4"
"price" => "1240"
]
2 => array:3 [▼
"product_id" => null
"quantity" => null
"price" => null
]
]
I have an array. I want to sum quantity & price from this array. How can I do that?
For example: sum of quantity will be 2+2+2 = 6 & price will be 500+700+620 = 1820
Advertisement
Answer
If you want sum all things together:
$sum = 0;
foreach($arr as $a) {
$quantity = $a['quantity'] ?? 0;
$price = $a['price'] ?? 0;
$sum += $quantity * $price;
}
but with your edit you should do like this:
$sumQuntity = 0;
$sumPrice = 0;
foreach($arr as $a) {
$sumQuntity += $a['quantity'] ?? 0;
$sumPrice += $a['price'] ?? 0;
}