PHP array_merge()


array_merge() function combines two or more arrays.

<?PHP
	$arr1=array(1,3,5,7,9);
	$arr2=array(2,4,6,8);
	$arr3=array_merge($arr1,$arr2);
	foreach($arr3 as $element) echo "$element, "; //1, 3, 5, 7, 9, 2, 4, 6, 8,
?>

If there are redundant values in the combined array, they will be saved as is.
<?PHP
	$arr1=array(1,3,5,7,9);
	$arr2=array(1,2,4,6,8);
	$arr3=array(1,2);
	$arr4=array_merge($arr1,$arr2,$arr3);
	foreach($arr4 as $element) echo "$element, "; //1, 3, 5, 7, 9, 1, 2, 4, 6, 8, 1, 2, 
?>

array_merge() also supports associative arrays.
<?PHP
	$arr1=array("apple"=>"carbon","rice"=>"carbon","nuts"=>"fat","meat"=>"protein");
	$arr2=array("corn"=>"carbon","fish"=>"protein");
	$arr3=array_merge($arr1,$arr2);
	foreach($arr3 as $key=>$val) echo "$key, $val; "; 
	//apple, carbon; rice, carbon; nuts, fat; meat, protein; corn, carbon; fish, protein;
?>

If redundant keys exist in the arrays to be combined, only the last occurence will be saved.
<?PHP
	$arr1=array("apple"=>"carbon","rice"=>"carbon","nuts"=>"fat","meat"=>"protein");
	$arr2=array("corn"=>"carbon","fish"=>"protein");
	$arr3=array("rice"=>"unknown","fish"=>"unknown");
	$arr4=array_merge($arr1,$arr2,$arr3);
	foreach($arr4 as $key=>$val) echo "$key, $val; "; 
	//apple, carbon; rice, unknown; nuts, fat; meat, protein; corn, carbon; fish, unknown; 
?>