Home > other >  Adding arrays with the same keys in PHP
Adding arrays with the same keys in PHP

Time:01-16

I'm looking for a way to add the contents of two arrays together in keywise fashion. Example:

$first_array = array("key_1" => 2, "key_2" => 3, "key_3" => 4);
$second_array = array("key_1" => 5, "key_2" => 6, "key_3" => 7);
$third_array = add_arrays($first_array, $second_array);

The expected result for $third_array should be "key_1" => 7, "key_2" => 9, "key_3" => 11.

Is there an existing function in PHP that does this? (I have made up "add_arrays()" for the purposes of the above example.) I'm trying not to reinvent the wheel if this already exists in PHP.

CodePudding user response:

You can use array_walk() its there in the PHP Manual, Array Functions section

As I am passing a reference to the first arrays item &$a1_item this will update the first_array with the summation.

$first_array = array("key_1" => 2, "key_2" => 3, "key_3" => 4);
$second_array = array("key_1" => 5, "key_2" => 6, "key_3" => 7);


function add(&$a1_item, $a1_key, $second_array) 
{
    $a1_item  = $second_array[$a1_key];
}

array_walk($first_array, 'add', $second_array);
print_r($first_array);

RESULTS

Array
(
    [key_1] => 7
    [key_2] => 9
    [key_3] => 11
)

OR you can simply copy the first array to a new array and then use that

$first_array = array("key_1" => 2, "key_2" => 3, "key_3" => 4);
$second_array = array("key_1" => 5, "key_2" => 6, "key_3" => 7);

$new_array = array_combine(array_keys($first_array), $first_array);
function add(&$a1_item, $a1_key, $second_array) 
{
    $a1_item  = $second_array[$a1_key];
}

array_walk($new_array, 'add', $second_array);
print_r($new_array);

RESULT

Array
(
    [key_1] => 7
    [key_2] => 9
    [key_3] => 11
)

CodePudding user response:

Here are two possible approaches that scale for summing up any number of arrays. Please read the inline comments for more insight on what's being done.

Sum Any Existing Keys

This approach uses two foreach loops, adding up values for any keys found in any array:

// Tuck arrays into a parent array to keep iteration simple
$arrays['first'] = array("key_1" => 2, "key_2" => 3, "key_3" => 4);
$arrays['second'] = array("key_1" => 5, "key_2" => 6, "key_3" => 7);
$arrays['third'] = array("key_1" => 1, "key_3" => 7, "key_7" => 2);

// Function: Sum Arrays By Key
function sum_arrays_by_key(array $arrays) {
    $sums = [];

    // Iterate each array:
    foreach($arrays as $arr_vals) {

        // Iterate their values:
        foreach($arr_vals as $key => $val) {

            // Initialize the summary key:
            $sums[$key] ??= 0;

            // Add up the value:
            $sums[$key]  = $val;
        }
    }
    return $sums;
}

$sums = sum_arrays_by_key($arrays);

print_r($sums);

Result:

Array
(
    [key_1] => 8
    [key_2] => 9
    [key_3] => 18
    [key_7] => 2
)

Recap: This sums up the values from the matching keys of any number of arrays, and doesn't require each array to have identical keys. (The third array doesn't have key_2, and has key_7, not found in the others.)

Sum by First Array's Keys

This approach uses array_sum() and array_column() and sums up the columns by iterating over the keys from the first array:

// Function: Sum Arrays Match Keys
function sum_arrays_match_keys(array $arrays) {
    $sums = [];

    // Get keys from the first array:
    $keys = array_keys(current($arrays));
    
    // Iterate keys:
    foreach($keys as $key) {

        // Sum up the columns:
        $sums[$key] = array_sum(array_column($arrays, $key));
    }
    return $sums;
}

$sums = sum_arrays_match_keys($arrays);

print_r($sums);

Result:

Array
(
    [key_1] => 8
    [key_2] => 9
    [key_3] => 18
)

You'll notice that key_7 from the third sample array was omitted, since it doesn't match the first array's keys that are the basis for columns fetched. You could easily modify the function to pass in your choice of keys and iterate over them instead.

You could also use this approach in place of the "double foreach" of the first sample to sum any existing keys, however you'd first have to extract the keys from each array and merge them together; which would defeat the simplicity of summing up columns in one loop here.

  •  Tags:  
  • Related