Calculate the Sum of Values of an Array

Recently I was working on a project that required me to sum up the array values (int) which was not hard at all but required me few seconds to think about it. I thought I will share this post with you guys and hopefully some of you will find this useful. So, here we go.

Think of about an array with bunch of integer values. To sum up the values you can use the following method.

<?php
// variable holds the array values
\$ar = array(1,2,3,4,5);
// total of the array values
echo array_sum(\$ar);
?>

In order to get the sum of this array values we are taking help from a native PHP function (array_sum). Once you have the values(int) on your array, this function do rest of the job. All you have to do is to echo out the sum.

Now, lets get little deep. Think of about an array that has multiple key and values. In other words you can think like number of individuals with their weekly salary and you need to find the sum of their salaries. Before we get started, please note that we would be using “foreach” loop to get the sum of our total. This is how you can do it.

<?php
// data in an array
\$ar = array(
'John'  => '125',
'Paul'  => '130',
'Chris' => '145');
// declaring the total variable
\$total = 0;
// run the loop
foreach (\$ar as \$key => \$val){
\$total += \$val; }
// sum of all the value
echo \$total;
?>

We are declaring the “total” variable to be “0” before the loop because we want the array values to be added and summed up using this variable. Every time we loop through the array, each value (\$val) gets added to the \$total variable and eventually we get the sum of all the values. I hope that helps.

References: array_sum, foreach