diank diank - 4 months ago 58
PHP Question

PHP merge 2 array with same key

Hi everyone how I can merge/push one array to another to specific keys? Here is my arrays:

// Array 1
Array
(
[1] => Array
(
[name] => test
)
)

// Array 2
Array
(
[1] => Array
(
[age] => 25
)
)


I want this result:

Array
(
[1] => Array
(
[name] => test
[age] => 25
)
)


I use PHP and will be very grateful if someone help me. Thanks in advance!

Answer
$arr = [ 1 => [ "name" => "Test" ] ];
$arr2 = [ 1 => [ "age" => 25 ] ];

foreach ($arr as $key => $value) {
     if (isset($arr2[$key])) {
        $arr[$key] = array_merge($value,$arr2[$key]);
     }
}

print_r($arr);

Check the output at https://eval.in/602680