PHP array_​merge Function



array_​merge() is an another PHP pre built / default array function, This function is basically allows user to merge one or more arrays into one array. array_​merge() merges the elements by appending them to the end of the previous element of array.

array_​merge() is an another PHP pre built / default array function, This function is basically allows user to merge one or more arrays into one array. array_​merge() merges the elements by appending them to the end of the previous element of array.

Syntax of array_​merge() :
array_merge(array1, array2, array3, …)

Parameter :
array1 (required) : Specifies an array
array2 (optional) : Another array
array3 (optional) : Another array

Return Type / Values : Returns the merged array.

Example 1 : We are merging 2 array into one array:

<?php
	$array1 = array("a"=>"orange", "b"=>"banana");
	$array2 = array("c"=>"peach", "b"=>"apple");
	print_r(array_merge($array1, $array2));
?>

Output will be :

Array 
( 
	[a] => orange 
	[b] => apple 
	 => peach 
)

Note : If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended. In the above example if you can see we have we banana and apple in b index but in output it is showing only the apple as it overwrite with second array.

Example 2 :

<?php
	$array1 = array("color" => "green", 3, 6);
	$array2 = array("x", "y", "shape" => "trapezoid", "color" => "red", 5);
	$result = array_merge($array1, $array2);
	print_r($result);
?>

Output will be :

Array 
( 
	[color] => red 
	[0] => 3 
	[1] => 6 
	[2] => x 
	[3] => y 
	[fruit] => grapes 
	[4] => 5 
)

Example 3 :

<?php
	$newarray = array(2=>"yello", 4=>"red");
	print_r(array_merge($newarray));
?>

Output will be:

Array 
	( 
		[0] => yello 
		[1] => red 
	)

Reference Article : https://www.php.net/manual/en/function.array-merge.php

In the previous post I described regarding the PHP array_​column Function Please check this article as well.

Hope this article helps you in PHP development and understandings of Array. Stay tuned for more PHP Tutorials, Hope you enjoyed reading, if you need the professional PHP, PHP Framework and Magento 2 Development we can help you, just Click on the Link and send me your requirements.