dlofrodloh
dlofrodloh

Reputation: 1744

How to add values in multidimensional array

I have a multidimentional array which stores values and I want to add the values of each element in the array and return an array of the total values.

I've created the following function which works, but it seems very bloated for it's purposes. Is there a simpler and cleaner way of doing the following?

function get_totals($metric_array){
    $totals['value1']=0;
    $totals['value2']=0;
    $totals['value3']=0;
    $totals['value4']=0;
    $totals['value5']=0;
    $totals['value6']=0;
    $totals['value7']=0;
    $totals['value8']=0;

    foreach ($metric_array as $metric){
        $totals['value1']=$totals['value1']+$metric['value1'];
        $totals['value2']=$totals['value2']+$metric['value2'];
        $totals['value3']=$totals['value3']+$metric['value3'];
        $totals['value4']=$totals['value4']+$metric['value4'];
        $totals['value5']=$totals['value5']+$metric['value5'];
        $totals['value6']=$totals['value6']+$metric['value6'];
        $totals['value7']=$totals['value7']+$metric['value7'];
        $totals['value8']=$totals['value8']+$metric['value8'];  
    }
    return $totals;
}

Upvotes: 0

Views: 63

Answers (2)

Dinesh Belkare
Dinesh Belkare

Reputation: 631

As I can see You are trying to return sum of columns.Your function can be optimized like this.

    function get_totals($metric_array){
        $totals = array();
        foreach ($metric_array as $metric){
            foreach ($metric as $key => $val){
                $totals[$key] += $val;
            }  
        }
        return $totals;
    }

Upvotes: 0

GolezTrol
GolezTrol

Reputation: 116180

You can construct the key value1, and make a for loop from 1 to 8. That'll save some code:

function get_totals($metric_array){
  for ($i = 1; $ <= 8; $i++) {
    $key = 'value' . $i;
    $totals[$key] = 0;
    foreach ($metric_array as $metric){
      $totals[$key] += $metric[$key];
    }
  }
  return $totals;
}

Upvotes: 2

Related Questions