faqts : Computers : Programming : Languages : PHP : Common Problems : Arrays

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

18 of 24 people (75%) answered Yes
Recently 7 of 10 people (70%) answered Yes

Entry

If we have array(1,2,3,4,5) how can we add the values of the array eg this example =10

Jun 20th, 2001 08:08
Philip Olson, Ben Udall, John Cassidy, Rada Eulen, Paul Routledge, unknown unknown,


Assuming our array of numeric values (to add) is as such :
  $array = array(4, 9, 33, 5);
As of PHP4.0.4 the function array_sum() exists, it's used as such :
  $sum   = array_sum($array); // 51
Or, one can always loop through the array, as such :
  reset($array);
  while (list(, $value) = each($array)) {
    $sum += $value;
  }
Or use foreach (PHP4+) :
  foreach ($array as $value) {
    $sum += $value;
  }
And in every case in the above, $sum will be equal to the sum of all 
values in the particular array.  If the above code does not make sense, 
then check out :
  http://www.php.net/manual/control-structures.foreach.php
  http://www.php.net/manual/language.operators.increment.php
  http://www.php.net/manual/function.array-sum.php