16

In PHP, (given that $a, $b and $c are arrays) is $a = array_replace($b, $c) always functionally identical to $a = $c + $b?

I can't seem to find any edge cases that would indicate otherwise.

(just working with one dimension, this question isn't concerned with recursion, ie: array_replace_recursive())


Edit: I found a note in a comment that suggests that the union operator will preserve references, but I haven't noticed array_replace() failing to do that.

Dan Lugg
  • 20,192
  • 19
  • 110
  • 174

2 Answers2

10

EDIT: Ah sorry, I didn't notice the arguments were reversed. The answer is yes, then, because the resulting array always has the two arrays merged, but while + gives priority to values in the first array and array_replace to the second.

The only actual difference would be in terms of performance, where + may be preferable because when it finds duplicates it doesn't replace the value; it just moves on. Plus, it doesn't entail a (relatively expensive) function call.


No. array_replace replaces elements, while + considers the first value:

<?php
print_r(array_replace([0 => 1], [0 => 2]));
print_r([0 => 1] + [0 => 2]);
Array
(
    [0] => 2
)
Array
(
    [0] => 1
)

To cite the manual:

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.

As for references, they are preserved in both cases.

Artefacto
  • 96,375
  • 17
  • 202
  • 225
  • Spectacular, thanks @Artefacto -- I figured they were, though I was concerned of some undocumented edge cases (*as I've noticed PHP is somewhat notorious for*) – Dan Lugg Dec 16 '11 at 17:27
  • 1
    I've found a nice image and description explain full difference: https://softonsofa.com/php-array_merge-vs-array_replace-vs-plus-aka-union/ – Ahmad Azimi Feb 25 '16 at 07:44
6

It should also be mentioned that array_merge also functions the same as array_replace if the supplied arrays have non-numeric keys.

mdpatrick
  • 1,082
  • 9
  • 12