php function for adding two arrays

  • 2020-05-07 19:23:25
  • OfStack

 
<?php 
function array_add($a,$b){ 
// Gets the intersection of two arrays based on the key name  
$arr=array_intersect_key($a, $b); 
// Through the first 2 Array if the key name does not exist with the first 1 Array, increasing the array element to the first 1 An array  
foreach($b as $key=>$value){ 
if(!array_key_exists($key, $a)){ 
$a[$key]=$value; 
} 
} 
// Calculates the sum of the array elements with the same key name, and replaces the values of the elements with the same key name in the original array  
foreach($arr as $key=>$value){ 
$a[$key]=$a[$key]+$b[$key]; 
} 
// Returns the added array  
return $a; 
} 
$a = array('0'=>'2','1'=>'4','3'=>'8','a'=>'100'); 
$b = array('0'=>'5','2'=>'4','b'=>'33','a'=>'22'); 
$arr=array_add($a,$b); 
print_r($arr); 
?> 

Related articles: