How to merge,combine,recursive an array in PHP

PHP has provided per-define functions to group different arrays into single. In many cases, you might need to merge two or more arrays, combine their elements, or even recursively navigate through nested arrays. In this tutorial, we will explore how to accomplish these tasks efficiently in PHP.

1:- array_merge()
2:- array_combine()
3:- array_merge_recursive()

Merge two arrays using array_merge()

We can merge two or more arrays using array_merge() and its syntax is quite simple-

$color = ['red','white'];
$color2 = ['black', 'blue'];
$final_array = array_merge($color, $color2);

Array ( 
   [0] => red
   [1] => white 
   [2] => black 
   [3] => blue 


$array1 = ['fruit'=>'', 'color'=>'orange'];
$array2 = ['color'=>'red'];
print_r(array_merge($array1, $array2));

Array ( 
    [fruit] =>
    [color] => red 

However, if the arrays contain numeric keys, the later value will not overwrite the previous/original value, but it will be appended and a new index will be allocated to it.

Merge two arrays using array_merge_recursive()

Now, we’ll use the same above example and see how array_merge_recursive() work efficiently to not override the parent key instead it uses the same key and add those different values inside it as an array.

Array (
 [a] => red 
 [b] => Array (
   [0] => green 
   [1] => yellow
 [c] => blue

Merge two arrays using array_combine()

The array_combine() function creates an array by using the elements from one “keys” array and one “values” array.

Combining arrays involves creating a new array with elements from both arrays. Unlike merging, this method does not eliminate duplicate values.

Array ( 
[Peter] => 35
[Ben] => 37
[Joe] => 43

Related Articles

Leave a Reply

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

Back to top button