How to merge two array with same keys without loop in PHP ?

Share Me
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Do you want to merge two array but you want without overwrite value then here you can see how to merge two array in following example. So now we have two array and we want to merge it with overwrite with any key then we fetch many problem.we can do like this two array :

My Array:

$array1 = [  
        '0'=> ['name'=>'shahriar','Surname'=>'Sagor'],  
        '1'=> ['name'=>'Code','Surname'=>'master'],  
       ];  
    $array2 = [  
        '0'=> ['name1'=>'jibon','Surname1'=>'ahmed'],  
        '1'=> ['name1'=>'joy','Surname1'=>'mahamud'],  
       ];  

AND You want to merge like that :

Output:

Array  
    (  
        [0] => Array  
            (  
                [name] => shahriar  
                [Surname] => sagor  
                [name1] => jibon  
                [Surname1] => ahmed  
            )  
      
        [1] => Array  
            (  
                [name] => code  
                [Surname] => master  
                [name1] => joy  
                [Surname1] => mahamud  
            )  
    )  

Then we want to make this as like array without any loop, then we can use array_map() and array_merge(). Now this both function will help us to make this output as we want like this way to use.

Example:

$result = array_map(function($array1,$array2){  
	return array_merge(isset($array1) ? $array1 : array(), isset($array2) ? $array2 : array());
 	},$array1,$array2);  
  
print_r($result)

Read Also : How to use Union query with Laravel Eloquent?

Thanks for read this, I hope it will you. You can also follow us onĀ Facebook.

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →