1

I'm looking to combine two arrays into one array, but I would like to keep the key values the same and accumulate their values into one.

Using PHP I'm looking for something like this:

//inputs
array(
   cat => 4,
   dog => 3,
   bug => 6

);

array(
   cat => 2,
   dog => 5,
   bug => 9,
   ant => 3

);


//output
array(
   cat => 6,
   dog => 8,
   bug => 15,
   ant => 3

);
1
  • you need to use loop for that Commented Jul 8, 2013 at 15:53

3 Answers 3

1

You could add the arrays by adding each of the indexes: (this assumes that your first array is array1 and so on)

<?php
for ($i = 1; $i <= 4; $i ++) {
    $array3[i] = $array1[i] + $array2[i];
}
?>

Assuming each of your arrays has 4 variables in it.

Sign up to request clarification or add additional context in comments.

Comments

0
function func(&$value, $key) {
    $value = (isset($value[1]) ? $value[0] + $value[1] : $value[0]);
}

$new_array = array_merge_recursive($array1, $array2);
array_walk($new_array, 'func');
print_r($new_array);

Comments

0
$final_array = array ();

// u can iterate and get the name of the key while doing so, like so
// add the first array
foreach ($array1 as $prop=>$val)
{
    $final_array[$prop]+=$val;
}


//add the second array
foreach ($array2 as $prop=>$val)
{
    $final_array[$prop]+=$val;
}

//result is in final_array

//or more efficiently, just add the second to the first
foreach ($array2 as $prop=>$val)
{
    $array1[$prop]+=$val;
}

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.