add the values of two different associative arrays in php . display unique key-values too in the result array -
this question has answer here:
- how sum values of array of same key? 13 answers
i need merge 2 associative arrays may or may not contain same key,if key same values need added , stored in resultant array
$array1 = array( 'a' => 5, 'b' => 10, 'c' => 6, 'k' = > 10 ); $array2 = array( 'a' => 100, 'c' => 200, 'd' => 30, 'k' => 10 );
how add above 2 associative arrays , receive following output/associative array -
$array2 = array( 'a' => 105, 'b' => 10, 'c' => 206, 'd' => 30, 'k' => 20 );
try
$array1 = array( 'a' => 5, 'b' => 10, 'c' => 6, 'k' => 10 ); $array2 = array( 'a' => 100, 'c' => 200, 'd' => 30, 'k' => 10 ); $sums = array(); foreach (array_keys($array1 + $array2) $key) { $sums[$key] = (isset($array1[$key]) ? $array1[$key] : 0) + (isset($array2[$key]) ? $array2[$key] : 0); } print_r($sums);
Comments
Post a Comment