Home > Backend Development > PHP Tutorial > http://www.hunanzhibo.com/ Function to add two arrays in php

http://www.hunanzhibo.com/ Function to add two arrays in php

WBOY
Release: 2016-07-29 08:45:44
Original
1325 people have browsed it

Copy the code The code is as follows:


function array_add($a,$b){
//Get the intersection of two arrays based on the key name
$arr=array_intersect_key($a, $ b);
//Traverse the second array, if the key name does not exist in the first array, add the array elements to the first array
foreach($b as $key=>$value){
if( !array_key_exists($key, $a)){
$a[$key]=$value;
}
}
//Calculate the sum of array elements with the same key name, and replace the elements corresponding to the same key name in the original array Value
foreach($arr as $key=>$value){
$a[$key]=$a[$key]+$b[$key];
}
//Return 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);
?>

The above introduces the function of adding two arrays in http://www.hunanzhibo.com/ php, including the content of http://www.hunanzhibo.com/. I hope that friends who are interested in PHP tutorials can helped.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template