DEV Community

Mehedi Hasan Sagor
Mehedi Hasan Sagor

Posted on

1 1

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

Billboard image

Deploy and scale your apps on AWS and GCP with a world class developer experience

Coherence makes it easy to set up and maintain cloud infrastructure. Harness the extensibility, compliance and cost efficiency of the cloud.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs