Skip to content
Advertisement

How to sum value from an Array in laravel? [closed]

     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;
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement