php

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.

Arrays in PHP are versatile and powerful data structures, often used to store collections of values. In this guide, we will explore the various ways to merge and combine arrays, including handling arrays recursively, using built-in PHP functions.

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-

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

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

// SECOND EXAMPLE

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

// OUTPUT
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.

In situations where you need to merge arrays that contain nested arrays, array_merge_recursive() is the go-to function. Instead of overwriting values with the same key, this function merges them into sub-arrays.

<?php
$a1=array("a"=>"red","b"=>"green");
$a2=array("c"=>"blue","b"=>"yellow");
print_r(array_merge_recursive($a1,$a2));
?>
// OUTPUT
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.

<?php
$fname1=array("Peter","Ben","Joe");
$age1=array("35","37","43");
$c=array_combine($fname1,$age1);
print_r($c);
// OUTPUT
Array ( 
[Peter] => 35
[Ben] => 37
[Joe] => 43
 ); 
?>

Custom Recursive Array Merge

Sometimes, array_merge_recursive() might not give you the desired results, especially when you’re merging associative arrays where you expect later values to overwrite previous ones. In such cases, you can write a custom recursive merge function.

function customArrayMergeRecursive(array &$array1, array &$array2) {
    foreach ($array2 as $key => $value) {
        if (is_array($value) && isset($array1[$key]) && is_array($array1[$key])) {
            customArrayMergeRecursive($array1[$key], $value);
        } else {
            $array1[$key] = $value;
        }
    }
    return $array1;
}

$array1 = ["fruit" => ["apple", "banana"], "color" => "red"];
$array2 = ["fruit" => ["cherry"], "color" => "blue"];

$customMerged = customArrayMergeRecursive($array1, $array2);
print_r($customMerged);

Output:

Array
(
    [fruit] => Array
        (
            [0] => cherry
        )
    [color] => blue
)

In this example, if the key exists and both values are arrays, it recursively merges them. Otherwise, it overwrites the value.

5. Conclusion

Merging arrays in PHP can be simple or complex depending on the structure of your arrays. The built-in functions array_merge(), array_combine(), and array_merge_recursive() cover most common use cases. For more control, especially in recursive scenarios, a custom merge function might be necessary.

Related Articles

Leave a Reply

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

Back to top button