What is the difference between array_replace and array_merge?

Asked

Viewed 475 times

4

I wonder what the difference is 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]);

Exit:

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

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

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

Exit:

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

  • When I should use one or the other?

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:

inserir a descrição da imagem aqui

Numerical arrays:

$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));

What we know of them:

Merge does not replace numbers.

Replace.

Addition operator does not add the elements existing in the last array that are not in the first.

Associative Arrays:

$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 of them:

In both replace and merge the values that match the keys are replaced and whatever you have is kept different between them.

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

In the third comparison the characteristics of the first case and the second.

Image of https://softonsofa.com.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.