1

I am trying to get the total sum of this array:

Array
(
[1] => 0
[2] => 1
[3] => Array
    (
        [0] => 1
        [1] => 1
        [2] => 1
    )

[4] => 1
[5] => 0
)

In this case the sum should be 5. I can't seem to get it to work. Can someone help me?

EDIT:

I have tried using array_sum (which obviously doesn't work) and a recursive array like this:

  $array_obj = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
  $sum = 0;
  foreach($array_obj as $key => $value) {
    if($key == '3')
      $sum += $value;
  }

Somehow this returns 20;

2
  • You will have tried many different options that failed. Why don't you share with us your tests? We will be glad to help you fixing your code Commented May 7, 2018 at 8:06
  • may you please publish complete code? Commented May 7, 2018 at 8:08

5 Answers 5

3

You can use array_walk_recursive() in combination with using an outer variable by reference:

$sum = 0;
array_walk_recursive($array, function($number) use (&$sum) {
    $sum += $number;
});
echo $sum;

In case an element of an array is an array itself, array_walk_recursive() will iterate through it. Otherwise it will call the function on the element.

Sign up to request clarification or add additional context in comments.

Comments

2

One option is to use array_walk_recursive

$arr = $arr = array(0,1,array(1,1,1,),1,0,);
$sum = 0;

array_walk_recursive( $arr, function($i) use(&$sum){
    $sum += $i;
});

$sum will result to 5

Doc: array_walk_recursive()

2 Comments

Looks like Philipps
Ohh.. I didn't realise that this approach has been answered.
1

Recursion comes to the rescue.

You can write a generic method, which handles summation for any array with any depth level.

Example:

$array = array(0, 1, 2, array(4, 5, array(7, 8)));

function sumArr($arr) {
    $sum = 0;
    foreach($arr as $v) {
        if (is_array($v)) {
            $sum += sumArr($v);
        } else {
            $sum += $v;
        }
    }
    return $sum;
}
// prints 27 as intended
echo sumArr($array);

3 Comments

Php has designed a specific function for this task. Please read the other answers.
Except that your answer was posted just a bit later. There is nothing wrong if one wants to understand how to do it manually and understand recursion concept in depth. Obviously author struggles with it. If usage of such function doesn't affect overall performance and doesn't change big O, then it is just a matter of personal preferences of how to calculate sum for multidimensional array.
Good news. I found an exact duplicate to close with. Such simple questions are never unique on StackOverflow.
1

In your try no need to add if condition if($key == '3')

  $array_obj = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
  $sum = 0;
  foreach($array_obj as $key => $value) {
      $sum += $value;
  }
  echo "sum : ".$sum; 

You are getting flat array and if condition restrict to add other keys value than 3. You was almost near.

Live Demo

Comments

1

The following code will work for any dimensional array:

$input = array(0,1,array(1,1,1),1,0);

function sum($arr){
  $sum=0;
  foreach($arr as $single){       
      if(is_array($single))
        $sum+= sum($single);
      else
        $sum+=$single;
    }
  return $sum;
}

echo sum($input);

Explanation: The above code will be executed as follows:

  1. go through every element of an array
  2. check the current element is another array or simple digit.
  3. if current element is an array go to step 1. otherwise sum up.

Final result will be returned.

7 Comments

Please never post Try this answers in StackOverflow. They are low value on StackOverflow because they do very little to educate the OP and future readers. Please improve this post to explain how it works and why researchers should use it.
The code was self explanatory. Silence is better when code speaks by itself. Anyway, thanks @mickmackusa
For someone that is familiar with php/coding, yes. But people of all levels come here for knowledge. Silence is not better when people what to understand why/how something works. This site is an ever growing resource of knowledge please care more for the content on this site.
Thanks. I agree with you. I will keep in mind for next time.
Thank you very much. Please do this as a habit -- you will help more people and inevitably earn more points if you do.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.