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,
4
  • 1
    Clear your question a bit more and tell me what is your complete output when you print result correctly also explain logic ? Commented Feb 11, 2019 at 11:27
  • 2
    array_count_values then. And what's the point for second array then? Commented Feb 11, 2019 at 11:29
  • It would be more useful if you would add one or two non-trivial examples. Commented Feb 11, 2019 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 Commented Feb 11, 2019 at 11:33

3 Answers 3

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

7 Comments

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
What is the expected output for that? I mean, the code I provide will output what you describe: 3v4l.org/2p0au. There must be some misunderstanding...
@BilalRehman check my code above i have tested and works fine for me
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...
@NewtonSingh, if you have something to say about your own code, please post it there, not here.
|
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);

Comments

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

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.