Hướng dẫn php sum array column

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

Show

array_sumCalculate the sum of values in an array

Description

array_sum(array $array): int|float

Parameters

array

The input array.

Return Values

Returns the sum of values as an integer or float; 0 if the array is empty.

Examples

Example #1 array_sum() examples

$a = array(2468);
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:

rodrigo at adboosters dot com

7 months ago

If you want to calculate the sum in multi-dimensional arrays:

function array_multisum(array $arr): float {
   
$sum = array_sum($arr);
    foreach(
$arr as $child) {
       
$sum += is_array($child) ? array_multisum($child) : 0;
    }
    return
$sum;
}
?>

Example:

$data =
[
   
'a' => 5,
   
'b' =>
    [
       
'c' => 7,
       
'd' => 3
   
],
   
'e' => 4,
   
'f' =>
    [
       
'g' => 6,
       
'h' =>
        [
           
'i' => 1,
           
'j' => 2
       
]
    ]
];

echo

array_multisum($data);//output: 28
?>

samiulmomin191139 at gmail dot com

7 months ago

//you can also sum multidimentional arrays like this;function arraymultisum(array $arr){
$sum=null;

        foreach(

$arr as $child){
       
$sum+=is_array($child) ? arraymultisum($child):$child;
    }
    return
$sum;
}

echo

arraymultisum(array(1,4,5,[1,5,8,[4,5,7]]));//Answer Will be
//40
?>

444

6 months ago

$total = 0;
foreach ($array as $key => $value){
   $total += $value;
}
Print "sum $total";