Given the folowing arrays:
$a1 = [
'name' => 'First Name',
'address' => [
'street' => 'Street 123',
'postcode' => '1234AB',
'city' => 'Amsterdam',
],
'kids' => [
0 => [
'name' => 'Kid 1',
],
1 => [
'name' => 'Kid 2',
],
],
'nationality' => 'NL',
];
$a2 = [
'name' => 'Second Name',
'address' => [
'street' => 'Street 456',
'postcode' => '1234AZ',
],
'kids' => [
0 => [
'name' => 'Kid 1',
],
1 => [
'name' => 'Kid 3',
],
],
];
When using array_merge()
, items on the highest level will always be overwritten:
$a3 = array_merge($a1, $a2);
// Is the same as
$a3 = [
'name' => 'Second Name',
'address' => [
'street' => 'Street 456',
'postcode' => '1234AZ',
],
'kids' => [
0 => [
'name' => 'Kid 1',
],
1 => [
'name' => 'Kid 3',
],
],
'nationality' => 'NL',
]
Then there is array_merge_recursive()
, which will turn scalars into arrays when merging:
$a3 = array_merge_recursive($a1, $a2);
// Is the same as
$a3 = [
'name' => [
0 => 'First Name',
1 => 'Second Name',
],
'address' => [
'street' => [
0 => 'Street 123',
1 => 'Street 456',
],
'postcode' => [
0 => '1234AB',
1 => '1234AZ',
],
'city' => 'Amsterdam',
],
'kids' => [
0 => [
'name' => 'Kid 1',
],
1 => [
'name' => 'Kid 2',
],
2 => [
'name' => 'Kid 1',
],
3 => [
'name' => 'Kid 3',
],
],
'nationality' => 'NL',
];
The code in this gist will overwrite scalar values, will (uniquely) add indexed arrays and will merge associative arrays.
$a3 = arrayMergeAlternate($a1, $a2);
// Is the same as
$a3 = [
'name' => 'Second Name',
'address' => [
'street' => 'Street 456',
'postcode' => '1234AZ',
'city' => 'Amsterdam',
],
'kids' => [
0 => [
'name' => 'Kid 1',
],
1 => [
'name' => 'Kid 2',
],
2 => [
'name' => 'Kid 3',
],
],
'nationality' => 'NL',
];