ItSolutionStuff.com

How to Merge Two Array with Same Keys without Loop in PHP?

By Hardik Savani • May 14, 2024
PHP

you want to merge two array but without overwrite value then you can see how to merge two array in following example.you have two array and you want to merge with overwrite with key then you fetch many problem. like this two array :

My Array:

$array1 = [

'0'=> ['name'=>'Hardik','Surname'=>'Savani'],

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

];

$array2 = [

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

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

];

AND You want to merge like that :

Output:

Array

(

[0] => Array

(

[name] => Hardik

[Surname] => Savani

[name1] => Harshad

[Surname1] => Pathak

)

[1] => Array

(

[name] => Harsukh

[Surname] => Makawana

[name1] => Vimal

[Surname1] => Kashiyani

)

)

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.

Example:

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

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

},$array1,$array2);

print_r($result);

Try this.........

Tags: PHP
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

How to Remove Duplicate Values from Array in PHP?

Read Now →

How to Convert Object to Array in Laravel?

Read Now →

How to Set Value as Key in PHP Array?

Read Now →

How to Convert Array Key to Lowercase in PHP?

Read Now →

How to Convert Object into Array in PHP?

Read Now →

How to Remove Specific Element by Value from Array in PHP?

Read Now →

How to Remove undefined Value from Array in JQuery?

Read Now →

How to Get Maximum Key Value of Array in PHP?

Read Now →

How to Remove Empty Values from Array in PHP?

Read Now →

How to Add Prefix in Each Key of PHP Array?

Read Now →

How to Get Minimum Key Value of Array in PHP?

Read Now →

How to Remove Null Values from Array in PHP?

Read Now →