array_sum

(PHP 4 >= 4.0.4, PHP 5)

array_sumВычисляет сумму значений массива

Описание

number array_sum ( array $array )

array_sum() возвращает сумму значений массива.

Список параметров

array

Входной массив.

Возвращаемые значения

Возвращает сумму значений в виде integer или float.

Список изменений

Версия Описание
4.2.1 PHP более ранних, чем 4.2.1, версий модифицировал переданный в качестве аргумента массив и конвертировал строки в числа (что в большинстве случаев означало конвертирование в 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

Коментарии

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";
?>
2003-07-30 06:14:29
http://php5.kiev.ua/manual/ru/function.array-sum.html
Hi people, if someone is searching a function that works also with multimension array, i suggest this :

<?php
function cw_array_count($a) {
  if(!
is_array($a)) return $a;
  foreach(
$a as $key=>$value
     
$totale += cw_array_count($value);
  return 
$totale;
}

$a[0][E][PS][P][a1]=1;
$a[0][E][PS][P][a2]=2;
$a[0][E][PJ][P][a2]=2;
$a[1][E][PS][E][a3]=3;

echo 
cw_array_count($a[0]);
// or
echo cw_array_count($a[0][E]);
?>

Bye, Bye.
R.Martina
2003-08-13 12:40:05
http://php5.kiev.ua/manual/ru/function.array-sum.html
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);
?>
2003-10-22 18:44:51
http://php5.kiev.ua/manual/ru/function.array-sum.html
For clarity, array indices containing boolean values such as TRUE and FALSE are added up as though they are 1 and 0 respectively.
2005-02-07 20:02:53
http://php5.kiev.ua/manual/ru/function.array-sum.html
Here's a function to return the sum of a portion of an array:

function array_partial_sum($array, $start, $length){
    $new_array = array_slice($array, $start, $length);
    return array_sum($new_array);
}

$array = array(1, 2, 3, 4, 5);
print array_partial_sum($array, 0, 3);  // prints 6
2005-03-01 18:37:16
http://php5.kiev.ua/manual/ru/function.array-sum.html
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;
  }
}
2005-03-15 21:06:53
http://php5.kiev.ua/manual/ru/function.array-sum.html
Not sure where else to put this, but I added something that determines the most commonly occuring item in an array.  Known Bugs: It will always return the first value if no mode are found, and the first mode found if more are found of same or lesser count.

<?php
function array_mode($array) {
 
$count = array();
 foreach (
$array as $item) {
 
$count[$item]++;
 }
 
$mostcommon "";
 
$iter 0;
 foreach (
$count as $k => $v) {
  if (
$v $iter) {
   
$mostcommon $k;
   
$iter $v;
  }
 }
 return array(
"mode" => $mostcommon"count" => $count[$mostcommon]);
}
?>
2005-08-12 12:22:03
http://php5.kiev.ua/manual/ru/function.array-sum.html
I ran into a situation where I only wanted to sum elements of an array for certain keys. For that, I wrote this function

<?

function array_sum_by_key()
{
   
$args func_get_args();
   
   
$arr array_shift($args);
           
   
$to_sum is_array($args[0]) ? $args[0] : $args;
   
   
$sum 0;

    foreach ( 
$arr as $k=>$v ) {
        if ( 
in_array($k$to_sum) ) {
           
$sum += $v;
        }
    }
   
    return 
$sum;
}

$arr = array (
   
'dog' => 1,
   
'cat' => 2,
   
'rat' => 4,
   
'mat' => 8,
   
'bat' => 16
);

echo 
array_sum_by_key($arr'dog''mat');

// Result: 9

?>

Alternatively, you can pass the keys to sum as an array

<?

$to_sum 
= array('dog''bat');

echo 
array_sum_by_key($arr$to_sum);

// Result: 17

?>
2005-09-27 16:06:15
http://php5.kiev.ua/manual/ru/function.array-sum.html
function array_avg(&$array)
{
  //**
    returns the average value of all array-values
    or false if no values in array (or not an array)
  **//

  if (!is_array($array) || count($array)==0) 
    return false;
  else
    return array_sum($array)/count($array);
} // array_avg()

Please add this function to PHP.
2005-11-04 05:57:01
http://php5.kiev.ua/manual/ru/function.array-sum.html
A simple example for numeric values :

<?PHP 

function array_average($arr){
$sum array_sum($arr);
$num sizeof($arr);
echo 
$sum/$num;
}

$myarray = array(1,2,3,4);
array_average($myarray); // displays 2.5 as average of 1,2,3,4

?>

[Arash Moslehi]
2006-03-17 17:13:14
http://php5.kiev.ua/manual/ru/function.array-sum.html
In reference to KageKonjou's array_mode function...

If you only want to know the value in the array that occurs most (and not the number of times it actually occured), you can use this short function.  It also suffers from the same problem in that if there is more than one mode, it will return only one.
<?php
   
function array_mode($array)
    {
        if(!
is_array($array)) return false;
       
asort(array_count_values($array));
        return 
array_pop($array);
    }
?>
2006-06-01 11:23:50
http://php5.kiev.ua/manual/ru/function.array-sum.html
Автор:
<?php
$array1 
= array('1'=>'1','2'=>'2','3'=>'3');
$array2 = array(          '2'=>'1','3'=>'2','4'=>'3');
$array3 = array(                  '3'=>'1','4'=>'2','5'=>'3');
$array  array_sum_values$array1$array2$array3 );
print_r($array);

/**
 * Sums the values of the arrays be there keys (PHP 4, PHP 5) 
 * array array_sum_values ( array array1 [, array array2 [, array ...]] )
 */
function array_sum_values() {
   
$return = array();
   
$intArgs func_num_args();
   
$arrArgs func_get_args();
    if(
$intArgs 1trigger_error('Warning: Wrong parameter count for array_sum_values()'E_USER_WARNING);
   
    foreach(
$arrArgs as $arrItem) {
        if(!
is_array($arrItem)) trigger_error('Warning: Wrong parameter values for array_sum_values()'E_USER_WARNING);
        foreach(
$arrItem as $k => $v) {
           
$return[$k] += $v;
        }
    }
    return 
$return;
}
/* result:
Array
(
    [1] => 1
    [2] => 3
    [3] => 6
    [4] => 5
    [5] => 3
)
*/
?>
2006-07-28 02:41:16
http://php5.kiev.ua/manual/ru/function.array-sum.html
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;
    }
  }
?>
2006-11-24 17:28:24
http://php5.kiev.ua/manual/ru/function.array-sum.html
This is a simple approach to subtract array, both indexed and associative.

  function array_sub($arr) {
    if (!is_array($arr) || count($arr) == 0) {
      return false;
    } else {
      // get first element
      $base = array_shift($arr);

      if (count($arr) == 1) {
        // If only one element, return its
        return $base;
      }

      foreach ($arr as $val) {
        $base -= $val;
      }

      return $base;
    }
  }

// example
$arr1 = array(3, 2, 3);
echo array_sub($arr1);   // Output: -2
$arr2 = array(3.5, 2, 3);
echo array_sub($arr2);   // Output: -1.5
$arr3 = array('a' => 3, 'b' => 2, 'c' => 3);
echo array_sub($arr3);   // Output: -2
2007-07-18 09:48:45
http://php5.kiev.ua/manual/ru/function.array-sum.html
Автор:
A much simpler algorithm for array_sub():

<?php
 
function array_sub($arr) {
    if (!
is_array($arr) || count($arr) == 0) {
      return 
false;
    } else {
     
// get first element
     
$base array_shift($arr);

      return 
$base array_sum($arr);
    }
  }
?>

This will return the exact same results that didikdwi's version.

However, didikdwi's result depends on knowing what the first value is. When this likely bug is removed, the code is:

<?php
 
function array_sub($arr){
   
$temp array_sum($arr);
    return ( 
$temp !== false ? -$temp false ); 
  }
?>
2007-08-16 19:10:20
http://php5.kiev.ua/manual/ru/function.array-sum.html
here is a function that can sum values like these :

$tab = array( 
                 0 => array ("val1" => 2,"val2" => 5)
                 1 => array ("val1" => 6,"val2" => 10)
                 "toto" => array ("val1" => 15,"val2" => 50)
                );

sum_subarrays_by_key( $tab, "val1" );

the function will sum all values with "val1" key in tab subarrays.

function sum_subarrays_by_key( $tab, $key ) {
       
        $sum = 0;
       
        foreach($tab as $sub_array) {
            $sum += $sub_array[$key];
        }
       
        return $sum;
       
    }

it can be transformed to be recursive and do also all depths possible in an array.

Hope it can be usefull!
2008-01-29 08:31:28
http://php5.kiev.ua/manual/ru/function.array-sum.html
Автор:
To elaborate on djyb2003 at yahoo dot fr. His function can be converted to recursive, but i've made a smaller function to do so:

<?php

 
function array_sum_all($array) {
   
$func create_function("&\$arr=0,\$key=0","static \$a=0; if(is_int(\$arr)) { \$a+=\$arr; } return \$a;");
   
array_walk_recursive($array,$func);
   return 
$func();
 }

$tab = array(
                 
=> array ("val1" => 2,"val2" => 5),
                 
=> array ("val1" => 6,"val2" => 10),
                 
"toto" => array ("val1" => 15,"val2" => 50)
                );
var_dump(array_sum_all($tab)); //This will output: int(88);
?>

hope this helps someone
2008-08-27 14:29:48
http://php5.kiev.ua/manual/ru/function.array-sum.html
<?php
/**
 * sum values in array
 *
 * @param array $arr
 * @param string [optional]$index
 * @return int result
 */
function array_sum_key$arr$index null ){
    if(!
is_array$arr ) || sizeof$arr ) < 1){
        return 
0;
    }
   
$ret 0;
    foreach( 
$arr as $id => $data ){
        if( isset( 
$index )  ){
           
$ret += (isset( $data[$index] )) ? $data[$index] : 0;
        }else{
           
$ret += $data;
        }
    }
    return 
$ret;
}
?>

With this function you can choose whether you sum specific keys in a multidim array, or a normalized array. it is designed to not trigger errors if a key is not set.
2008-09-05 04:30:39
http://php5.kiev.ua/manual/ru/function.array-sum.html
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);
   
   
}

?>
2008-10-06 10:01:29
http://php5.kiev.ua/manual/ru/function.array-sum.html
Автор:
Average array values, ignoring zero values:

<?php
function array_average_nonzero($arr) {
   return 
array_sum($arr) / count(array_filter($arr));
}
?>

<?php
$arr 
= array(1,2,3,0,0);
echo 
array_average_nonzero($arr); // returns 2
echo array_sum($arr) / count($arr); // returns 1.2
?>
2010-02-17 10:24:43
http://php5.kiev.ua/manual/ru/function.array-sum.html
<?php
function avrg()
{
 
$count func_num_args();
 
$args func_get_args();
 return (
array_sum($args) / $count);
}
?>

This function calculates average of numbers given as arguments. Examples:
avrg(100, 200, 300) - returns 200.
avrg(5, 6) - returns 5.5.
avrg('foo') - returns 0.
2011-01-07 04:21:39
http://php5.kiev.ua/manual/ru/function.array-sum.html
There was a case where I had a complex array, multi-dimesional and non-symmetric (not all elements of a sub-array were arrays themselves)
Although all the leaf elements of this array were numbers. In case you have two variables like that and you wanted to add all the values of the right variable to the left then you would need a function like below.

This is a recursive function which adds the values of two multidimensional arrays with the same key structure:

<?php
function multiDimArrayAdd(& $left$right)    //created by George Pligor
{
    if(
is_array($left) && is_array($right))
    {
        foreach(
$left as $key => $val)
        {
            if( 
is_array($val) )
            {
               
multiDimArrayAdd($left[$key], $right[$key]);
            }
           
$left[$key] += $right[$key];
        }
    }
}
?>
2011-06-01 15:12:33
http://php5.kiev.ua/manual/ru/function.array-sum.html
If the array is a result from mysql_fetch_array, it contains every value twice and the sum will be double.
2011-09-03 19:37:01
http://php5.kiev.ua/manual/ru/function.array-sum.html
As mysql_fetch_array returns associative and numeric indexes, you can simply use a flag.

<?php
$result 
mysql_query("SELECT id, name FROM mytable");
$row mysql_fetch_array($resultMYSQL_NUM);
array_sum($row);
?>

Hope it helps.
2011-10-15 06:02:20
http://php5.kiev.ua/manual/ru/function.array-sum.html
If you want to sum all values (horizontal or vertical) use this function:

<?php

function sumArray($array$params = array('direction' => 'x''key' => 'xxx'), $exclusions = array()) {

    if(!empty(
$array)) {
   
       
$sum 0;
   
        if(
$params['direction'] == 'x') {
       
           
$keys array_keys($array);
           
            for(
$x 0$x count($keys); $x++) {
           
                if(!
in_array($keys[$x], $exclusions))
                   
$sum += $array[$keys[$x]];
           
            }
           
            return 
$sum;
       
        } elseif(
$params['direction'] == 'y') {
       
           
$keys array_keys($array);
       
            if(
array_key_exists($params['key'], $array[$keys[0]])) {
           
                for(
$x 0$x count($keys); $x++) {
               
                    if(!
in_array($keys[$x], $exclusions))
                       
$sum += $array[$keys[$x]][$params['key']];
                   
                }
                   
                return 
$sum;
           
            } else return 
false;
       
        } else return 
false;
   
    } else return 
false;

}

?>

Some examples now:

<?php

$array1 
= array('myKey1' => 2'myKey2' => 5'myKey3' => 8);
$array2 = array(array('myKey1' => 2'myKey2' => 5'myKey3' => 8), array('myKey1' => 2'myKey2' => 5'myKey3' => 8));

/*Sum an array*/
print_r(sumArray($array1)); //outputs: 15

/*Sum an array without adding "myKey2" key*/
print_r(sumArray($array1, array('direction' => 'x'), array('myKey2'))); //outputs: 10

/*Sum a multi-dimensional array horizontally without adding "myKey3" key*/
print_r(sumArray($array2[0], array('direction' => 'x'), array('myKey3'))); //outputs: 7

/*Sum a multi-dimensional array vertically (by "myKey1" key) without adding [0] row*/
print_r(sumArray($array2, array('direction' => 'y''key' => 'myKey1'), array('0'))); //outputs: 2

?>
2012-05-06 21:17:45
http://php5.kiev.ua/manual/ru/function.array-sum.html

    Поддержать сайт на родительском проекте КГБ