PHP append one array to another
Given two array arr1 and arr2 and the task is to append one array to another array.
Examples:
Input : arr1 = [ 1, 2 ]
arr2 = [ 3, 4 ]
Output : arr1 = [ 1, 2, 3, 4 ]
Input : arr1 = [ "Geeks", "g4g" ]
arr2 = [ "GeeksforGeeks" ]
Output : arr1 = [ "Geeks", "g4g", "GeeksforGeeks" ]
Using array_merge function: This function returns a new array after merging the two arrays.
Example:
<?php$arr1 = array("Geeks", "g4g");$arr2 = array("GeeksforGeeks", "Computer science portal"); // Get the merged array in the first array itself.$arr1 = array_merge($arr1, $arr2); echo "arr1 Contents:"; // Use for each loop to print all the array elements.foreach ($arr1 as $value) { echo $value . "\n";}?> |
Output:
arr1 Contents: Geeks g4g GeeksforGeeks Computer science portal
Using array_push Method: This method pushes the second array element in the first array in-place.
Example:
<?php$arr1 = array(1, 2);$arr2 = array(3, 4); // arr2 elements are being pushed in the arr1.array_push($arr1 , ...$arr2); echo "arr1 = "; // Use for each loop to print all the array elements.foreach ($arr1 as $value) {echo $value . ' ';}?> |
Output:
arr1 = 1 2 3 4
Note: Another way to do it is by ‘ + ‘ but it gives fatal warning in the newer versions, hence it is not recommended.



