phparraysreplacemerging-data

Merge two associative arrays and give value priority to one array


I'm trying to combine 2 arrays and replace the the $x array cells with the $y cells. I have this code:

$x = array (
    'a'  => '1',
    'b'  => '2',
    'd'  => '6'
);

$y = array (
    'a'  => '3',
    'b'  => '4',
    'c'  => '5'
);

How can I get an array like this:

a => 3,
b => 4,
c => 5,
d => 6

?


Solution

  • Use array_merge function.

    $z = array_merge($x, $y);
    

    Will output:

    Array
    (
        [a] => 3
        [b] => 4
        [d] => 6
        [c] => 5
    )