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?
Related Topics
PHP: Remove all empty elements from string array
Tip | 0 Comments
JavaScript: Create and Use Arrays
Info | 0 Comments
Send Form Input as an Array to PHP Script
Tip | 0 Comments
Lazarus: Load File as Byte Array and save Byte Array as File
Tutorial | 0 Comments
PHP: Write array to individual Variables
Tutorial | 0 Comments
PHP: Fill Array with Sequence of Numbers or Characters
Tutorial | 0 Comments
PHP: Determine Number of Elements in an Array / Length of Array
Tip | 0 Comments
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.
Yes, it can be much easier. Just use the function array_sum() of PHP:
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