• Post category:PHP

Great Examples to Merge Two or more Arrays in PHP

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:

merge two arrays in php

  1. In the above code, we have created two arrays $dark and $light.
  2. If we want to combine these two values and store them into variable $colors, we need to use PHP array_merge() function.
  3. Inside the function, we need to give the array name you are going to combine.
  4. 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:

combine three arrays in PHP

  1. In the above code, we have created three arrays $dark, $light, and $darklight.
  2. 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.
  3. 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.

Leave a Reply