Skip to content

Instantly share code, notes, and snippets.

@orvigas
Created January 31, 2018 21:47
Show Gist options
  • Save orvigas/36f55a4d375cd7806ffb014671115c50 to your computer and use it in GitHub Desktop.
Save orvigas/36f55a4d375cd7806ffb014671115c50 to your computer and use it in GitHub Desktop.
Function to sum two arrays in php
<?php
/**
* Function to sum two arrays
*
* @param array $a First array to merge
* @param array $b Second array to merge which gonna be returned by function
*
* @author Orlando Villegas Galán <orvigas@gmail.com>
* @return $b
*/
function sumArrays(array $a = [], array $b = []) {
foreach ($a as $k => $v) {//Iterate along the '$a' array, getting key value pair for every array position
if(array_key_exists($k, $b)){//Check if '$a' key exist in '$b'
//If key exist into '$b' array
if(is_array($v)){//Check if value of key is an array
//If value is an array
$b[$k] = sumArrays($b[$k],$v);//The function is called itself recursively
}else{
//Otherwise
$b[$k]+=$v;//Accumulates the '$a' value in '$b' key position
}
}else{
//Otherwise
$b[$k]=$v; //Create key node in '$b'
}
}
//Return merged '$b'
return $b;
}
/** Array declaration **/
$a = [4,"a" => 3, "b" => ["ba" => 1, "bc" => 2], "c" => ["ca" => 4, "cb" => 3]];
$b = [5,"a" => 2, "b" => ["ba" => 4, "bc" => 3], "c" => ["ca" => 4]];
print_r(sumArrays($a, $b));
/** Output **/
/*
Array
(
[0] => 9
[a] => 5
[b] => Array
(
[ba] => 5
[bc] => 5
)
[c] => Array
(
[ca] => 8
[cb] => 3
)
)
*/
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment