-11 Vote

PHP: Sum over all elements of an array

Question by PlasmaTV | 2012-02-19 at 18:35

I want to calculate the sum of all elements of an array of numbers. So far, I use the following function for that:

$arr = array(1,2,3);
$sum = 0;
 
foreach ($arr as $value) {
   $sum += $value;
}
 
echo $sum; // output: 6

Isn't there an easier way to do it?

ReplyPositiveNegative
-2Best Answer2 Votes

Yes, it can be much easier. Just use the function array_sum() of PHP:

$arr = array(1,2,3);
$sum = array_sum($arr);
echo $sum; // output: 6

If the array contains strings, array_sum() tries to convert the strings to a number or adds 0 if this is not possible.
2012-02-21 at 23:23

ReplyPositive Negative
Reply

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.