php merge associative arrays by key code example
Example 1: array merge in php
/* Array merge is basically use to merge the two array data. */
<?php
$a1=array("red","green");
$a2=array("blue","green","yellow");
print_r(array_merge($a1,$a2));
?>
/*
Output:
Array ( [0] => red [1] => green [2] => blue [3] => green [4] => yellow )
*/
<?php
$a1=array("a"=>"red","b"=>"green");
$a2=array("c"=>"blue","b"=>"yellow");
print_r(array_merge($a1,$a2));
?>
/*
Output:
Array ( [a] => red [b] => yellow [c] => blue )
*/
/* In above example you can check the difference in output
it takes all values of both array in final output, but not in associative array you can check.
because one value gets overwritten by same key reference in both array.
*/
Example 2: php array merge for associative arrays
<?php
$array1 = array('key1' => 'test1', 'key2' => 'test2');
$array2 = array('key3' => 'test3', 'key4' => 'test4');
$resultArray = array_merge($array1, $array2);
$resultArray = $array1 + $array2;
Example 3: php merge array with same value
function custom_array_merge(&$array1, &$array2) {
$result = Array();
foreach ($array1 as $key_1 => &$value_1) {
foreach ($array2 as $key_1 => $value_2) {
if($value_1['name'] == $value_2['name']) {
$result[] = array_merge($value_1,$value_2);
}
}
}
return $result;
}
Example 4: array merge with same key in php
Input : $a1=array("a"=>"raj", "b"=>"striver");
$a2=array("z"=>"geeks", "b"=>"articles");
Output :
Array
(
[a] => raj
[b] => Array
(
[0] => striver
[1] => articles
)
[z] => geeks
)