Ahmed Imad Touil Ahmed Imad Touil - 1 month ago 24
PHP Question

How to sum over multiple fields in an array

i have a charges model that contain Price And Quantity , i want to multiply Price and Quantity and sum the results and update a table named bill with final results , here is my array

[
[
"Title" => "Price 1",
"Quantity" => "1",
"Price" => "1",
],
[
"Title" => "Price 2",
"Quantity" => "232",
"Price" => "32632",
],
[
"Title" => "Price 3",
"Quantity" => "11",
"Price" => "2115",
],
]

Answer

Assuming that $billItems is your initial array, you can do this in one line:

$grandTotal = array_sum(array_map(function($item) { return $item['Quantity'] * $item['Price']; }, $billItems));