Merge Two Arrays PHP
Learn how to merge two arrays in PHP with examples. To combine two arrays, we need to use the array_merge function. This function accepts one or more array variables as arguments. So, you can merge two or more arrays using the array_merge function.
syntax:
array_merge(arrayvar1, arrayvar2, ... , arrayvarN);
Ex: Merging two arrays
<?php
$dark = array('black', 'brown', 'blue');
$light = array('white', 'silver', 'yellow');
// merging two arrays to variable colors
$colors = array_merge($dark, $light);
print_r($colors);
?>
Output:
- In the above code, we have created two arrays $dark and $light.
- If we want to combine these two values and store them into variable $colors, we need to use PHP array_merge() function.
- Inside the function, we need to give the array name you are going to combine.
- Then print $colors using print_r() function, see the output two array values are displayed.
Ex: Merging Three arrays
<?php
$dark = array('black', 'brown', 'blue');
$light = array('white', 'silver', 'yellow');
$darklight = array('darkgreen', 'lightgreen');
// merging three arrays to variable colors
$colors = array_merge($dark, $light, $darklight);
print_r($colors);
?>
Output:
- In the above code, we have created three arrays $dark, $light, and $darklight.
- If we want to combine these three values and store them into variable $colors, we need to use PHP array_merge() function. We need to pass the arrayname as parameter.
- Then print $colors using print_r() function, see the output three array values are displayed.
I hope you have understood a little about how to merge two arrays. If you have any doubts about this then please comment below.