Calculating the Sum of an Array in php

The array_sum() function adds up the values in an indexed or associative array:

$sum = array_sum(array);

For example:

<?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";
?>
$scores = array(98, 76, 56, 80);
$total = array_sum($scores); // $total = 310

Leave a Comment