1

I want to combine two arrays into single array by adding the duplicate values, for example,

$first = array('one','two','one');
$second = array(10,5,30);

Expected result would be,

$third = array(

       'one' => 40,
       'two' => 5
           );

Here I have added the two numbers which is corresponded to repeated position.

Thanks in advance!

2
  • What you have tried so far? Post your attempts too Commented Jun 21, 2016 at 8:44
  • I was tried array_combine() but it doesn't return expected result, because associative array doesn't allow duplicate values Commented Jun 21, 2016 at 8:46

4 Answers 4

1

Try

$first = array('one','two','one');
$second = array(10,5,30);

$third  = array();
foreach ($first as $f_k=>$f_v)
{
    if(isset($new_array[$f_v]))
        $third[$f_v] +=$second[$f_k];
    else
        $third[$f_v] = $second[$f_k];
}
print_r($third);
Sign up to request clarification or add additional context in comments.

Comments

1

Make a new array and insert into the value of first as key and second as value, also make the addition on duplicate.

Working demo

$first = array('one','two','one');
$second = array(10,5,30);

$third = array();
foreach($first as $k => $v){
    if(isset($third[$v]))
        $third[$v] += $second[$k];
    else
        $third[$v] = $second[$k];
}
print_r($third);

Comments

1

Simple solution using array_walk function:

$result = [];
array_walk($first, function($v, $k) use(&$result, $second){
    $result[$v] = (isset($result[$v]))? ($result[$v] + $second[$k]) : $second[$k];
});

print_r($result);

The output:

Array
(
    [one] => 40
    [two] => 5
)

Comments

0
  Simple and working code
   <?php
      $first = array('one','two','one');
      $second = array(10,5,30);
      $result = array_combine_($first ,$second );
      echo $result;
     function array_combine_($keys, $values)
     {
       $result = array();
       foreach ($keys as $i => $k) {
            $result[$k][] = $values[$i];
       }
       $result = myfunction($result);
       return    $result;
      } 

      function myfunction($result)
      {
        foreach($result as $key=>$value)
        {
          if(is_array($value))
          {
               $new_array[$key] = array_sum($value);
          }
          else
          {
              $new_array[$key] = $value;
          }
        }   
      return    $new_array;
    }
 ?>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.