0

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;
}

2 Answers 2

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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;
    }

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.