stijnb1234
stijnb1234

Reputation: 184

Merge 2 arrays into 1 array in PHP

I've 2 arrays:

{"1":"red"}
{"1":"green","2":"red"}

It should remove 1 = green and replace it with 1 = red. Key 2 must simply remain.

So, I want an array like this:

{"1":"red","2":"red"}

How can I do that in PHP?

Upvotes: 1

Views: 58

Answers (1)

Syscall
Syscall

Reputation: 19780

You could use the operator + :

$a = [1 => "red"] ;
$b = [1 => "green", 2 => "red"] ;
print_r($a + $b) ;

Outputs :

Array
(
    [1] => red
    [2] => red
)

From documentation :
The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.

Upvotes: 1

Related Questions