PDA

View Full Version : Perform addition to a array of integers


joshuadavid2007
10-03-2007, 02:51 PM
Hi, sometimes you would want to total up all an array of integers. I came across that when i was thinking how to make a pie graph...


<?php

function sumEnum(array $enum)
{
for ($x=0; $x<count($enum); $x++)
{
(preg_match("/[0-9]/", $enum[$x])==1) ? $total+=$enum[$x] : die("Element ".$x." not integer.");
}
return $total;
}

$nums=array(2, 4, 6, 9, 12, 15);
echo sumEnum($nums);

?>


the code above takes an array as the argument, then it tests if each element is a integer, if it is, its value is gets added to $total, else, it shows an error message. then it returns $total's value.

there you have it, the answer is 48, for the example above.

please comment and if u need any functions to save coding time, let me know, i'll do it free. thank you !

dumpfi
10-03-2007, 03:23 PM
There is no need to reinvent the wheel: array_sum() (http://www.php.net/manual/en/function.array-sum.php)

dumpfi

joshuadavid2007
10-04-2007, 03:59 AM
sorry, i did not notice that.