Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge two associative arrays by pushing their values into a new array [closed]

Tags:

arrays

merge

php

I have the following two arrays:

$arrFoo = array(
    'a' => 12,
    'b' => 17,
);
$arrBar = array(
    'a' => 9,
    'c' => 4,
);

And i want the resulting array to look like this:

$arrResult = array(
    'a' => array ( 12, 9 ),
    'b' => array ( 17 ),
    'c' => array ( 4 ),
);

Is there a native PHP function to achieve this without using foreach?

like image 350
Setyl Avatar asked Nov 18 '25 08:11

Setyl


1 Answers

<?php

$arrFoo = array(
    'a' => 12,
    'b' => 17,
);
$arrBar = array(
    'a' => 9,
    'c' => 4,
);

$arrResult = array_merge_recursive($arrFoo, $arrBar);

var_dump($arr);

?>

With the array_merge_recursive you can merge the arrays in the way you're asking for. http://php.net/manual/en/function.array-merge-recursive.php

like image 160
Jesper Avatar answered Nov 19 '25 22:11

Jesper