0

I have the following array like so

$foo = [
    a => 0,
    b => 0,
    c => 0,
    d => 0
];

$bar = [
    c => 3,
]

How can I merge $foo and $bar in such a way that the output is like this

$foobar = [
    a => 0,
    b => 0,
    c => 3,
    d => 0
]

I have tried array_diff and array_intersect but didn't get any result.

1
  • 1
    Its time to try array_replace() :) Commented Aug 23, 2019 at 10:28

3 Answers 3

1

See the array-replace function. The following snippet should work:

<?php
$foo = [
    a => 0,
    b => 0,
    c => 0,
    d => 0
];

$bar = [
    c => 3,
];

$merged = array_replace($foo, $bar);
print_r($merged);
?>

Output:

Array ( [a] => 0 [b] => 0 [c] => 3 [d] => 0 )
Sign up to request clarification or add additional context in comments.

Comments

0

array_replace_recursive($foo, $bar);

Comments

0
$merge=array_merge($foo,$baar);


print_r($merge);



Output


[a] => 0 [b] => 0 [c] => 3 [d] => 0 

Second parameter make overide to first parameter

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.