Merge Two Arrays Together In PHP
Code snippet for how to Merge Two Arrays Together In PHP with sample and detail explanation
In PHP, merging of two or more arrays into a single array is a frequently encountered need. This short article aims to make that task easier for both beginners and experienced PHP developers alike, with a simple, comprehensive example.
Code snippet for Merging Arrays in PHP
Below is a simple PHP code snippet that illustrates the merging of two arrays:
<?php
$array1 = ["apple", "banana", "cherry"];
$array2 = ["dragon fruit", "elderberry", "figs"];
$combinedArray = array_merge($array1, $array2);
print_r($combinedArray);
?>
Upon running this code, your output should look something like this:
Array
(
[0] => apple
[1] => banana
[2] => cherry
[3] => dragon fruit
[4] => elderberry
[5] => figs
)
Code Explanation for Merging Arrays in PHP
The PHP array_merge()
function is utilized to merge two or more arrays into one array. Here is a breakdown of how it works step-by-step:
- Define Two Arrays: At first, two arrays
$array1
and$array2
are declared and initialized with some elements.
$array1 = ["apple", "banana", "cherry"];
$array2 = ["dragon fruit", "elderberry", "figs"];
- Merge the Arrays: The
array_merge()
function is then used to combine the two arrays,$array1
and$array2
, into a new array$combinedArray
. This new array now holds all elements from both the original arrays.
$combinedArray = array_merge($array1, $array2);
- Print the Combined Array: Here, the
print_r()
function is used to print all the elements of$combinedArray
. This will display all the merged elements onto the screen.
print_r($combinedArray);
In PHP, the order of arrays given as arguments to array_merge()
influences the order of elements in the resulting array. The array that is passed first will have its elements placed first in the merged array. And of course, more than two arrays can be merged at once, just by passing more arrays as arguments to the array_merge()
function. This approach is simple and efficient for merging arrays in PHP.