Signup/Sign In

How to merge two or more arrays into one array in PHP?

Answer: Using array_merge() function

We can merge two or more arrays in PHP using the array_merge() function. This function accepts one or more arrays and returns a new array having all the elements of the input array/arrays.

Example: Merger using array_merge() function

In the given example, we have merged two arrays $arr1 and $arr2 into the single array $new_arr by using the array_merge() function.

<!DOCTYPE html>  
<html> 
<head>
	<title>Merge two or more arrays into one array</title>
</head> 
<body>  
	<?php
		$arr1 = array("HTML", "CSS", "JavaScript", "Bootstrap");
		$arr2 = array("Nodejs", "MongoDB");

		$new_arr = array_merge($arr1, $arr2);
		print_r($new_arr);
	?>
</body>  
</html>  


Array ( [0] => HTML [1] => CSS [2] => JavaScript [3] => Bootstrap [4] => Nodejs [5] => MongoDB )

Merger Array with string keys

In the above example, we have merged the two arrays with elements. Now, we are going to merge the array having string keys. If the two or more arrays have the same string key, then the last occurred value of that key will overwrite the value of that particular key.

Example: Merge arrays with string keys

In the given example, we have merged the two arrays having string keys using array_merge() function.

<!DOCTYPE html>  
<html> 
<head>
	<title>Merge two or more arrays into one array</title>
</head> 
<body>  
	<?php
		$empId_1 = array("John" => 1, "Jerry" => 2, "Harry" => 3);
		$empId_2 = array("Jack" => 4, "James" => 5, "Jerry" => 6);

		$new_arr = array_merge($empId_1, $empId_2);
		print_r($new_arr);
	?>
</body>  
</html>  


Array ( [John] => 1 [Jerry] => 6 [Harry] => 3 [Jack] => 4 [James] => 5 )

Conclusion

In this lesson, we have learned how to merge two or more arrays into a single array in PHP. The array_merge() function merges two or more arrays into a single array. If two or more arrays have the same string keys, then the last occurred value of that key will be the value of that key in a new array.



About the author:
I am the founder of Studytonight. I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development.