array_sum

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

array_sum 对数组中所有值求和

说明

number array_sum ( array $array )

array_sum() 将数组中的所有值相加,并返回结果。

参数

array

输入的数组。

返回值

所有值的和以整数或浮点数的结果返回,array 为空时则返回 0

范例

Example #1 array_sum() 例子

<?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";
?>

以上例程会输出:

sum(a) = 20
sum(b) = 6.9

User Contributed Notes

p dot troxler at hispeed dot ch 26-Apr-2017 06:39
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.
didatus at dynarize dot de 21-Sep-2014 06:21
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)
hdeus at yahoo dot com 06-Oct-2008 04:01
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);
   
   
}

?>
herenvardo at gmail dot com 25-Nov-2006 12:28
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;
    }
  }
?>
punchto at hotmail dot com 16-Mar-2005 04:06
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;
  }
}
ncheung at maine dot rr dot com 08-Feb-2005 03:02
For clarity, array indices containing boolean values such as TRUE and FALSE are added up as though they are 1 and 0 respectively.
mucello NOO SPAM @ weatherimages dOt org 23-Oct-2003 12:44
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);
?>
drverieevil at REMOVEMEasenne dot org 30-Jul-2003 12:14
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";
?>