How to merge two array in PHP?

Diffrent method to merge two array in PHP

1. The array_merge function

The array_merge() function is a built-in function that is used to merge one or more arrays. The new array contains the elements of the first array followed by the elements of the second array and so on.

Example 1
<?php

$firstArray = ["One", "Three"];
$secondArray = ["Five", "Seven", "Nine"];

$mergedArray = array_merge($firstArray, $secondArray);

var_dump($mergedArray);

?>
Output:
array(5) {
    [0]=> string(3) "One"
    [1]=> string(5) "Three"
    [2]=> string(4) "Five"
    [3]=> string(5) "Seven"
    [4]=> string(4) "Nine"
}
Example 2:
<?php

$firstArray = ["One", "Three"];
$secondArray = ["Five", "Seven", "Nine"];

$mergedArray = $firstArray + $secondArray;

var_dump($mergedArray);

?>
2. Using array_merge_recursive() function

If you need to merge array recursively. If the arrays contains nested arrays, you can use ‘array_merge_recursive()’. This function merges array recursively, combining values of the same keys into arrays.

<?php

$firstArray = ["f" => "first", "s" => "second" ];

$secondArray = ["s" => "second", "t" => "third" ];

$mergedArray = array_merge_recursive($firstArray, $secondArray);

print_r($mergedArray);

?>
Output:
Array (
    [f] => first 
    [s] => Array (
        [0] => second
        [1] => two
    )
    [t] => third
)
  • ‘array_merge()’ : Concatenates arrays and reindexes numerically.
  • ‘array_merge_recursive() ‘ : Merges arrays recursively, combining values of the same keys.

I hope this tutorial help you.

Leave a Reply

Your email address will not be published. Required fields are marked *