Array function to sum values with same key

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Reviresco
Forum Contributor
Posts: 172
Joined: Tue Feb 19, 2008 4:18 pm
Location: Milwaukee

Array function to sum values with same key

Post by Reviresco »

Is there an array function to add together values that have identical keys?

For example, an array with:

red=>4,
blue=>3,
red=>5

would be returned:

red=>9,
blue=>3
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Array function to sum values with same key

Post by Christopher »

You can't have duplicate keys in an array like that. I would need to be:

Code: Select all

array(
     array('color'=>'red', 'amount'=>4),
     array('color'=>'blue, 'amount'=>3),
     array('color'=>'red, 'amount'=>5),
);
(#10850)
Reviresco
Forum Contributor
Posts: 172
Joined: Tue Feb 19, 2008 4:18 pm
Location: Milwaukee

Re: Array function to sum values with same key

Post by Reviresco »

Oops, forgot I was thinking of comparing two arrays here.

Example:

array1:

red=>3,
blue=>2

array2:

red=>4,
blue=>3

and I want to return:

red=>7,
blue=>5
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Re: Array function to sum values with same key

Post by Chris Corbyn »

Code: Select all

<?php
 
function array_sum_combine(/* $arr1, $arr2, ... */)
{
  $return = array();
  $args = func_get_args();
  foreach ($args as $arr)
  {
    foreach ($arr as $k => $v)
    {
      if (!array_key_exists($k, $return))
      {
        $return[$k] = 0;
      }
      $return[$k] += $v;
    }
  }
  return $return;
}
 
 
var_dump(array_sum_combine(array('red' => 1, 'green' => 3), array('bue' => 9, 'red' => 2), array('red' => -1, 'green' => 4)));
 
/*
 array (
  red => 2,
  green => 7,
  blue => 9
)
*/
Untested.
Post Reply