1

I'm not getting this right when trying to sum values of keys that are same within an associative array. I thought it's gonna be easy task, but it ain't the case so please...

I'm expecting following result:

 1 -->(7) 
2 -->(14)

Here's the array:

 $array = array( 1=>4, 2=>8, 1=>3, 2=>6, );

Here's what i tried since:

$sum= array();

foreach ($array as $key => $value){ $sum[$key] += $value;} print_r($sum);

Anyway, there's no loop performed at all, since it's returning this result,

Array ( [1] => 3 [2] => 6 );

and an error,

 Undefined offset: 1 

I thought maybe there's a PHP function to handle it, but I'll be glad for any help.

alexis
  • 43
  • 7
  • Something i didn't know. Just found a different approach based on what you said and it works great, thank you for helping – alexis Aug 25 '16 at 21:58

1 Answers1

0

What you want is impossible. Arrays cannot have duplicate keys:

php > $arr = array(1=>2, 1=>500);
php > var_dump($arr);
array(1) {
  [1]=>
  int(500)  // hey! where'd "2" go?
}

If you want to store multiple values in a single key, then that key has to point to an array:

$arr = array();
$arr[1] = array(1, 500);
var_dump($arr);
php > var_dump($arr);
array(1) {
  [1]=>
  array(2) {
    [0]=>
    int(1)
    [1]=>
    int(500)
  }
}
Marc B
  • 356,200
  • 43
  • 426
  • 500
  • Hi Marc, thank u for your support. Based on your advise and that from @Paul Crovella, i tried a different approach trying to isolate each key within an array. Got so well the desired result, but still the persistent error: Undefined offset: 1 Undefined offset: 7 on each key... What i did looks like this: $arr = array( array(1=> 500), array(1=> 20), array(7=> 5)); $arraySum = array(); foreach ($arr as $key => $arrChilds) { foreach ($arrChilds as $key2 => $value) { $arraySum[$key2]+= $value; } }print_r($arraySum); – alexis Aug 25 '16 at 18:03
  • The second approach worked fine since i found out on stackoverflow how to get rid of the notices. Just wanna say thanks again. http://stackoverflow.com/questions/1496682/how-to-sum-values-of-the-array-of-the-same-key/9938193#9938193 – alexis Aug 25 '16 at 22:01