2

I've got the problem. Here is my code:

$a = ['elm1' => 1, 'elm2' => []];
$b = ['elm1' => 2, 'elm2' => [3]];
$c = array_replace_recursive($b, $a);

In $c I expect to see ['elm1' => 1, 'elm2' => []], however I get ['elm1' => 1, 'elm2' => [3]]. It does not replace 'elm2' => [3] with 'elm2' => [].

Is this some kind of feature or this is a bug in array_replace_recursive?

Thank you.

0

2 Answers 2

2

Instead of array_replace_recursive you need simple array_replace as

$a = ['elm1' => 1, 'elm2' => []];
$b = ['elm1' => 2, 'elm2' => [3]];
$c = array_replace($b, $a);
print_r($c);//['elm1' => 1, 'elm2' => []]

Fiddle

Sign up to request clarification or add additional context in comments.

2 Comments

But you are using array_replace_recursive.
I think anant have to explain the above answer @b0s3
0

Use array_merge():-

<?php

$a = ['elm1' => 1, 'elm2' => []];
$b = ['elm1' => 2, 'elm2' => [3]];
$c = array_merge($b,$a); //it will check the indexes in both array and if indexes are same then first array value will remain on that index second will replace. 

echo "<pre/>";print_r($c);
?>

Output:- https://eval.in/395368

2 Comments

array_merge will replace all the values for a corresponding key of sub-array while array_replace_recursive replace only the keys which match, rest remain same..
array_merge will work over here but the OP need array_replace instead @b0s3 @anantkumarsingh you need to explain why array_merge you have used too

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.