# Sum values of multi-dimensional array in PHP

How would I calculate the sum of these two values inside this multi-dimensional array?

``````Array
(
[Dec 01, 2013] => Array
(
[COM] => Array
(
[C] => Array
(
[T] => 620.25
[U] => 24.75
)

)

)

)
``````
PHPWeb Development

Last Comment
DanielAttard
gplana

if your array is on a variable called \$a try this:

\$sum = 0;
foreach(\$e1 in \$a) {
foreach(\$e2 in \$e1){
foreach(\$e3 in \$e2){
foreach(\$e4 in \$e3){
\$sum += \$e4;
}
}
}
}
// here the \$sum variable has the sum of the values.
gplana

THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
SOLUTION
Marco Gasi

THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
gplana

The marqusG solution is easier than mine, however my solution works for any array with 4 dimensions (as the array of your example).

MarqusG solution will only work on this specific example (with these values) while my solution will work for any 4-dimension array.

Hope it helps. Regards.
Marco Gasi

Yes, it's true. Depending on your specific needs, one solution is better than the other: if you know  the array structure, the array keys and the exact position of the values you need to sum, my solution is more concise and less expensive in terms of resources since it doesn't require to loop through the whole array.

But if you need a more abstract and flexible routine, then gplana's solution is the one which fits you needs.

Reading the question, I have choosen the quicker solution. :)

Cheers
Ray Paseur

http://php.net/manual/en/function.array-sum.php
DanielAttard

Thanks to everyone for the comments.  I learned from all of them.
PHP

PHP is a widely-used server-side scripting language especially suited for web development, powering tens of millions of sites from Facebook to personal WordPress blogs. PHP is often paired with the MySQL relational database, but includes support for most other mainstream databases. By utilizing different Server APIs, PHP can work on many different web servers as a server-side scripting language.

125K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts

TRUSTED BY