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.

2 Answers 2

11

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.

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

2 Comments

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)
I've found a nice image and description explain full difference: softonsofa.com/…
6

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

1 Comment

this is more a comment than an answer to the question :)

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.