Dark

Light

Dark

Light

Scroll to top

Get total from loop in php or Sum values in foreach loop php

In your case IF you want to go with foreach loop than

$sum = 0;
foreach($group as $key=>$value)
{
   $sum+= $value;
}
echo $sum;

But if you want to go with direct sum of array than look on below for your solution :

$total = array_sum($group);

for only sum of array looping is time wasting.

array_sum — Calculate the sum of values in an array

<?php
$a = array(2, 4, 6, 8);
echo "sum(a) = " . array_sum($a) . "\n";

$b = array("a" => 1.2, "b" => 2.3, "c" => 3.4);
echo "sum(b) = " . array_sum($b) . "\n";
?>

The above example will output:

sum(a) = 20
sum(b) = 6.9
Author avatar
Amitpal Singh
https://amitpalsingh.com

Post a comment

Your email address will not be published. Required fields are marked *