Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : Array Functions : array_sum

array_sum

Calculate the sum of values in an array (PHP 4 >= 4.0.4, PHP 5)
number array_sum ( array array )

Example 279. array_sum() examples

<?php
$a
= array(2, 4, 6, 8);
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

Related Examples ( Source code ) » array_sum





Code Examples / Notes » array_sum

didikdwi

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


kagekonjou

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]);
}
?>


punchto

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;
 }
}


jodymickey

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);
}
?>


mucello noo spam @ weatherimages dot org

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

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


herenvardo

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


mroach

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


mcrm

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


adam

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


darianlassan

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.


ncheung

For clarity, array indices containing boolean values such as TRUE and FALSE are added up as though they are 1 and 0 respectively.

info

Don't use number_format() before array_sum()...it won't work correctly, if you have a summary...

moslehi atsign gmail dot com

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]


coder

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 );
 }
?>


tobias schlemmer

<?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 < 1) trigger_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
)
*/
?>


Change Language


Follow Navioo On Twitter
array_change_key_case
array_chunk
array_combine
array_count_values
array_diff_assoc
array_diff_key
array_diff_uassoc
array_diff_ukey
array_diff
array_fill_keys
array_fill
array_filter
array_flip
array_intersect_assoc
array_intersect_key
array_intersect_uassoc
array_intersect_ukey
array_intersect
array_key_exists
array_keys
array_map
array_merge_recursive
array_merge
array_multisort
array_pad
array_pop
array_product
array_push
array_rand
array_reduce
array_reverse
array_search
array_shift
array_slice
array_splice
array_sum
array_udiff_assoc
array_udiff_uassoc
array_udiff
array_uintersect_assoc
array_uintersect_uassoc
array_uintersect
array_unique
array_unshift
array_values
array_walk_recursive
array_walk
array
arsort
asort
compact
count
current
each
end
extract
in_array
key
krsort
ksort
list
natcasesort
natsort
next
pos
prev
range
reset
rsort
shuffle
sizeof
sort
uasort
uksort
usort
eXTReMe Tracker