Tuesday, 28 August 2018

Merge two associative arrays by pushing their values ​​into a new array


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 smart way to achieve this without using foreach?

<?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

0 comments:

Post a Comment