How can I sum all key values and then remove duplicate keys ?

My example array:
$eg=array("105"=>"3", "106"=>"1", "122"=>"7", "105"=>"1", "310"=>"3", "105"=>"5", "310"=>"2");

I want to output an array that will have sumed the values and removed duplicate keys:

[105]=9
[106]=1
[122]=7
[310]=5

("105"=>"9", "106"=>"1", "122"=>"7", "310"=>"5");

Thank you very much,
B.

    Array keys have to be unique, so I don't think your plan will work. Try print_r($eg) to see that your duplicate keys are not even being stored like you think they are.

    If there is a way to store an array with duplicate keys (and that's a BIG if), here is how you could do what you're wanting to do...

    sort($eg);
    $new = array();
    
    foreach ($eg as $k => $v) {
        if (array_key_exists($k, $new)) {
            $new[$k] += $v;
        } else {
            $new[$k] = $v;
        }
    }
    

    There are probably faster or more elegant solutions, but I haven't had my coffee yet. 😉 And I don't think your plan will work anyway. Could you do this with multiple input arrays to get around the duplicate key restriction?

      I did not know an array is allowed to have duplicate keys?

      In my mind
      $eg["105"] is always $eg["105"]

      How do you get duplicate keys?
      With different values?
      But maybe it is possible.

      In your way to assign perhaps. But at least This wont work:

      <?php
      
      $eg["105"] = "3";
      $eg["105"] = "1";
      $eg["105"] = "5";
      
      print_r($eg);
      
      ?>

      About this I do not know

      <?php
      
      $eg[105] = "3";    // key is integer
      $eg["105"] = "5"; // key is string
      
      print_r($eg);
      
      ?>
        Write a Reply...