parent root
PHP: array_sum - Manual

array_sum

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

array_sumCalculate the sum of values in an array

Description

array_sum ( array $array ) : number

array_sum() returns the sum of values in an array.

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

<?php
$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:

sum(a) = 20
sum(b) = 6.9
add a noteadd a note

User Contributed Notes 9 notes

up
96
mucello NOO SPAM @ weatherimages dOt org
15 years ago
If you want to find the AVERAGE of the values in your array, use the sum and count functions together.  For example, let's say your array is $foo and you want the average...

<?php
$average_of_foo
= array_sum($foo) / count($foo);
?>
up
8
didatus at dynarize dot de
5 years ago
If you want to check if there are for example only strings in an array, you can use a combination of array_sum and array_map like this:

<?php

function only_strings_in_array($arr) {
    return
array_sum(array_map('is_string', $arr)) == count($arr);
}

$arr1 = array('one', 'two', 'three');
$arr2 = array('foo', 'bar', array());
$arr3 = array('foo', array(), 'bar');
$arr4 = array(array(), 'foo', 'bar');

var_dump(
   
only_strings_in_array($arr1),
   
only_strings_in_array($arr2),
   
only_strings_in_array($arr3),
   
only_strings_in_array($arr4)
);
?>

This will give you the following result:
bool(true)
bool(false)
bool(false)
bool(false)
up
1
ncheung at maine dot rr dot com
14 years ago
For clarity, array indices containing boolean values such as TRUE and FALSE are added up as though they are 1 and 0 respectively.
up
-1
drverieevil at REMOVEMEasenne dot org
16 years ago
If some array elements arent integers, function will change them to integers (content of array will not change) type and then sum them.

Example:
<?php
$foo
[] = "12";
$foo[] = 10;
$foo[] = "bar";
$foo[] = "summer";
echo
array_sum ($foo); //same as echo "22";
?>
up
-19
punchto at hotmail dot com
14 years ago
Microsoft Excel - SUMIF()

function sumif($array,$criteria,$sum_array){
  if(is_array($array) && is_array($sum_array) && trim($criteria)!= ""){
    $array_count = (count($array) < count($sum_array)) ? count($array):count($sum_array);
    for($i=0;$i<$array_count;$i++){
      if(ereg("^<",$criteria)){
        $value = ereg_replace("^<","",$criteria);
        $result += $array[$i] < $value ? $sum_array[$i]:0;
      }
      elseif(ereg("^>",$criteria)){
        $value = ereg_replace("^>","",$criteria);
        $result += $array[$i] > $value ? $sum_array[$i]:0;
      }
      else{
        $value = $criteria;
        $result += $array[$i] == $value ? $sum_array[$i]:0;
      }
     
    }
    return $result ? $result:0;
  }
}
up
-30
herenvardo at gmail dot com
12 years ago
I'm not sure if something similar already exists, but I needed it so I made it:
<?php
 
/* Performs a pitagoric sum of the elements in $arr
   The pitagoric sum of a set of values is the square root of
   the sum of the sqare power of each value. So, for a, b, c
   it's sqrt(a^2 + b^2 + c^2) */
  /* If any element of $arr is an array itself, the array_sum
   will be used. Alternatively, the values could be used by
   recursion. Returns the integer part (floor) */
 
function array_pitag_sum($arr) {
    if(
is_array($arr) {
     
$ret = 0;
      foreach(
$arr as $i) {
        if(
is_array($i)) {
         
$s = array_sum($i);
         
$ret += $s*$s;
        } else {
         
$ret += $i*$i;
        }
      }
      return
floor(sqrt($ret));
    } else {
      return
$arr;
    }
  }
?>
up
-30
hdeus at yahoo dot com
10 years ago
Here is how you can multiply two arrays in the form of matrixes using a bit of matrix algebra (M*M).
By calling the function multiplyMatrix, you will be multiplying two sparse matrixes (zeros need not be included in the array for the operation to be performed).

<?php
$M
= array(
0=>array(1=>1,4=>1),
1=>array(2=>1,3=>1),
3=>array(1=>1),
4=>array(5=>1),
5=>array(6=>1)
);

$M1 = multiplyMatrix($M, $M); //multiplying $M by itself

echo '<pre>';print_r($M1);echo '</pre>';

function
multiplyMatrix($M1, $M2)
    {
#Helena F Deus, Oct 06, 2008
##Multiply two matrixes; $M1 and $M2 can be sparse matrixes, the indexes on both should match
       
if(is_file($M1)) {$matrix1 = unserialize(file_get_contents($M1));}
        else
$matrix1 = $M1;
       
           
       
#transpose M2
       
$M2t = transpose($M2);
       
        foreach (
$M2t as $row=>$tmp) {
           
##sum the result of the value in the col multiplied by the value in the vector on the corresponding row
               
               
foreach ($M1 as $row1=>$tmp1) {
                   
                   
$multiply[$row1] = array_rproduct($tmp,$tmp1);
                   
                    if(!
$multiply[$row1]){
                          exit;
                        }
                }
               
                foreach (
$multiply as $row1=>$vals) {
                   
                   
$sum[$row][$row1]=array_sum($vals);
                }
               
        }
   
   
$r=transpose($sum);
   
    return (
$r);
    }

function
transpose($M)
{
foreach (
$M as $row=>$cols) {
           
            foreach (
$cols as $col=>$value) {
                 if(
$value)
                
$Mt[$col][$row]=$value;
            }
        }
       
ksort($Mt);
       
return (
$Mt);           
}

function
array_rproduct($a1, $a2)
{
   
   
    foreach (
$a1 as $line=>$cols) {
       
$a3[$line] = $a1[$line]*$a2[$line];
        foreach (
$a2 as $line2=>$cols2) {
           
$a3[$line2] = $a1[$line2]*$a2[$line2];
        }
    }   
   
ksort($a3);
   
   
    return (
$a3);
   
   
}

?>
up
-12
j_mullings at hotmail dot co dot uk
1 year ago
Nice and clean if you know what I mean:

function makeRecursive($ar = "")
{
    $toflat = array( $ar );
    $res = array();
    while (($r = array_shift($toflat)) !== NULL)
        foreach ($r as $v)
            if (is_array($v))
                $toflat[] = $v;
            else
                $res[] = $v;
    return $res;
}
$data = [0,0,0,[0,0,[0,1,0,],0],0];
echo array_sum(makeRecursive($data));
up
-54
p dot troxler at hispeed dot ch
2 years ago
array_sum can be used to caculate the cross sum in a very short way:

array_sum(str_split('17243'))

php frameworks like rexo do it like this; it's faster then do it by iteration.
To Top
parent root