0
<?php
$keys = array(1,1,2,1,1);
$values = array(1,1,1,1,1);
$result = array_combine ($keys, $values);
?>

I want to add the second array values. For example $result will display the output as

$result[1] = 4, // it will add the all values for the $keys of 1 ,
$result[2] = 1,
Qirel
  • 25,449
  • 7
  • 45
  • 62
  • 1
    Clear your question a bit more and tell me what is your complete output when you print result correctly also explain logic ? – Newton Singh Feb 11 '19 at 11:27
  • 2
    `array_count_values` then. And what's the point for second array then? – u_mulder Feb 11 '19 at 11:29
  • It would be more useful if you would add one or two non-trivial examples. – trincot Feb 11 '19 at 11:32
  • See, I have arrays that will be names product id, second array is product quantity,, So product id = {1,5,65,56,1} and QQuantity is {5,6,5,6,5} So answer for product 1 will be 10 – Bilal Rehman Feb 11 '19 at 11:33

3 Answers3

1

You could use a plain foreach loop. For given arrays $keys and $values this will produce $result:

$result = [];
foreach($keys as $i => $key) {
    $result[$key] = (isset($result[$key]) ? $result[$key] : 0) + $values[$i];
}
trincot
  • 317,000
  • 35
  • 244
  • 286
  • No see this example array of products is 5,5,5,5,4,4,4,4,4,3 | array of quantities is 1,1,1,1,1,1,1,1,1,6 | This means product 5 has 4 quantities , product 4 has 5 quantities and product 3 has 6 – Bilal Rehman Feb 11 '19 at 11:40
  • What is the expected output for that? I mean, the code I provide will output what you describe: https://3v4l.org/2p0au. There must be some misunderstanding... – trincot Feb 11 '19 at 11:43
  • @BilalRehman check my code above i have tested and works fine for me – Newton Singh Feb 11 '19 at 11:48
  • BTW, this code produces the same results as the answer that was posted later, and where you comment "Exactly this", so now I am really confused... – trincot Feb 11 '19 at 11:48
  • @NewtonSingh, if you have something to say about your own code, please post it there, not here. – trincot Feb 11 '19 at 11:49
  • I see both comments at a time, so I tried second, This works too. – Bilal Rehman Feb 11 '19 at 11:56
  • Then why did you say "No" in your first comment? – trincot Feb 11 '19 at 11:57
1

Based on what you're expecting to achieve, this is a possible solution:

$keys = array(1,1,2,1,1);
$values = array(1,1,1,1,1);

$total = [];

foreach($keys as $index => $key){
    if(!array_key_exists($key, $total)){
        $total[$key] = 0;
    }

    $total[$key] += $values[$index];
}

print_r($total);
0

You can do like this

$keys = array(1,1,2,1,1);
$values = array(1,1,1,1,1);

$ids = $result = [];
foreach($keys as $index => $key) {
   if (in_array($key, $ids)) {
       $result[$key] += $values[$index]; 
    } else {
       $result[$key] = $values[$index]; 
    }

   $ids[] = $key;
 }

  echo"<pre>";
  print_r($result);
Newton Singh
  • 332
  • 3
  • 9