Forum PHP 2017

array_sum

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

array_sum配列の中の値の合計を計算する

説明

number array_sum ( array $array )

array_sum() は、配列の中の値の合計を整数または float として返します。

パラメータ

array

入力の配列。

返り値

値の合計を整数または float として返します。 array が空の場合は 0 を返します。

例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

add a note add a note

User Contributed Notes 8 notes

up
62
mucello NOO SPAM @ weatherimages dOt org
13 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
9
ncheung at maine dot rr dot com
12 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
7
didatus at dynarize dot de
2 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
0
p dot troxler at hispeed dot ch
2 months 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.
up
1
drverieevil at REMOVEMEasenne dot org
13 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
-6
punchto at hotmail dot com
12 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
-15
herenvardo at gmail dot com
10 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
-23
hdeus at yahoo dot com
8 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);
   
   
}

?>
To Top