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.

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.

<?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
 ); 
?>

Related Articles

Leave a Reply

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

Back to top button