What is the difference between array_replace and array_merge?

4

I would like to know the difference between array_replace and array_merge , because in some cases the two seem to have similar behaviors.

Example:

  $informacoes = ['nome' => 'wallace', 'idade' => 36];

  array_replace($informacoes, ['idade' => 26]);

Output:

[
    "nome" => "wallace",
   "idade" => 26,
]

In the case of array_merge , we have the same result:

array_merge($informacoes, ['idade' => 26]);

Output:

[
    "nome" => "wallace",
   "idade" => 26,
]
  • What is the main difference between the two?

  • When should I use one or the other?

asked by anonymous 01.04.2016 / 13:47

1 answer

10

For associative arrays, which is your example both work in the same way.

If you analyze this example by comparing array_replace vs array_marge vs union operator, you will see that each array type has its differential:

Numericalarrays:

$a=array(1,2,3);$b=array(2,3,4);var_dump(array_merge($a,$b));var_dump(array_replace($a,$b));var_dump(($a+$b));

Whatweknowaboutthem:

Mergedoesnotreplacenumbers.

Replacereplaces.

Additionoperatordoesnotaddtheelementsinthelastarraythatarenotinthefirstarray.

AssociativeArrays:

$a=array("batman" => "loser", "superman" => "win", "SuicideSquad" => "Awesome");
$b = array("batman" => "win", "superman" => "loser", "movie" => "Good");


var_dump(array_merge($a, $b));
var_dump(array_replace($a, $b));
var_dump(($a + $b));

What we know about them:

In both replace and merge, the values that hit the keys are replaced with whatever is different between them.

In addition it ignores the same keys and adds only what is different, there is no substitution.

In the third comparative, the characteristics of the first case and the second case are configured.

Image of link .

    
01.04.2016 / 14:18