DEV Community

Mehedi Hasan Sagor
Mehedi Hasan Sagor

Posted on

PHP merge two arrays on the same key AND value

Today what you are going to learn:
Do you need to merge two array however you need without overwrite cost then right here you could see how to merge array in following lesson. So now we've two array and we need 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'=>'Sagor','Surname'=>'Savani'],  

    '1'=> ['name'=>'Harsukh','Surname'=>'Makawana'],  

   ];  

$array2 = [  

    '0'=> ['name1'=>'Harshad','Surname1'=>'Pathak'],  

    '1'=> ['name1'=>'Vimal','Surname1'=>'Kashiyani'],  

   ];  
Enter fullscreen mode Exit fullscreen mode

AND You want to merge like that :

Result:-

Array  

(  

    [0] => Array  

        (  

            [name] => Sagor  

            [Surname] => Savani  

            [name1] => Harshad  

            [Surname1] => Pathak  

        )  

    [1] => Array  

        (  

            [name] => Harsukh  

            [Surname] => Makawana  

            [name1] => Vimal  

            [Surname1] => Kashiyani  

        )  

)  
Enter fullscreen mode Exit fullscreen mode

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

==>>

$result = array_map(function($array1,$array2){

return array_merge(isset($array1) ? $array1 : array(), isset($array2) ? $array2 : array());

},$array1,$array2);  
Enter fullscreen mode Exit fullscreen mode

print_r($result);

Read More

Latest comments (0)