1

I am stuck, and unable to code the sum of a multi-dimensional array with different types: below is an example instance.

$multi_dimes_array = array(
    "1"=>array
    (1,2,5,6,7),
    "2"=> "Apple",
    "3"=> array("1"=>array('some_more',
                'banana',
                'ship',array(1,5,6,7,array(4,4,4,4))))
);

My code looks like:

foreach ($multi_dimes_array as $val) {           
  if(is_array($val))
  {
    $total = $total + $val;
  }
}

but I get an error.

2
  • what do you want to sum? 1,2,5,6,7 or 4,4,4? Commented Nov 10, 2015 at 9:09
  • I want to calculate sum of the given array.Its a sample array.I have unknown nth level array having numbers as well as letters. Commented Nov 10, 2015 at 9:16

2 Answers 2

1

You should implement a recursive function:

function deep_array_sum($arr) {
    $ret = 0;
    foreach($arr as $val) {
        if (is_array($val))
            $ret += deep_array_sum($val);
        else if(is_numeric($val))
            $ret += $val;
    }
    return $ret;
}
Sign up to request clarification or add additional context in comments.

Comments

0

The way i see it, you require a recursive function or a whole lot of fors,ifs and whiles. So recursive it is.

function array_sums($arraypart)
{
  if(!is_array($arraypart))
  {
   return intval($arraypart);
  }
  else
  {
      $sub_sum = 0;
      foreach($arraypart as $new_part)
      {
          $sub_sum += array_sums($new_part);
      }
      return $sub_sum;
  }
}

Something along these lines perhaps? It goes like this: if it is not an array, try to get its integer (or float) value and return it. (i saw you had some string too, that could be dangerous if not parsed, actually how do you plan to add the strings?)

if it is an array, foreach of its elements, call the function again, sum their returns, and return them yourself.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.