1

I have two arrays and would like to combine / merge / put them together.

$arr1 = array(
    0 => array(1, 2),
    1 => array(5, 6)
);

$arr2 = array(
    0 => array(2, 3),
    1 => array(6, 7)
);    

come_together_right_now($arr1, $arr2); // the missing function?

and the result would be:

Array ( 
    [0] => Array ( 
        [0] => 1 
        [1] => 2 
        [2] => 3 
    )
    [1] => Array ( 
        [0] => 5 
        [1] => 6 
        [2] => 7 
    )

There are way too many array functions! array_merge and array_combine and the recursive alternatives seem to replace the values and they don't preserve numeric keys. How do I do this?

Jacob Raccuia
  • 1,666
  • 1
  • 16
  • 25
  • Related: [Merge two arrays containing objects and remove duplicate values](https://stackoverflow.com/q/10572546/2943403) – mickmackusa Sep 13 '22 at 06:01

3 Answers3

3

Assuming that they will always have the same keys!

$result = array();

foreach($arr1 as $key=>$array) {
    $result[$key] = array_merge($array, $arr2[$key]);
}
ka_lin
  • 9,329
  • 6
  • 35
  • 56
2

I might be late of answering this question but this might help you simply using array_map,array_merge and array_unique function like as

$result = array_map('array_unique',array_map('array_merge',$arr1,$arr2));
print_r($result);

Output

Array ( 
    [0] => Array ( 
        [0] => 1 
        [1] => 2 
        [2] => 3 
    )
    [1] => Array ( 
        [0] => 5 
        [1] => 6 
        [2] => 7 
    )

Demo

Narendrasingh Sisodia
  • 21,247
  • 6
  • 47
  • 54
0

Synchronously iterate the arrays to access their rows. Merge rows, remove duplicates, then re-index the elements.

Code: (Demo)

var_export(
    array_map(
        fn(...$rows) => array_values(array_unique(array_merge(...$rows))),
        $arr1,
        $arr2
    )
);
mickmackusa
  • 43,625
  • 12
  • 83
  • 136