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