Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array_replace() vs. union operator in PHP

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.

like image 488
Dan Lugg Avatar asked Dec 16 '11 16:12

Dan Lugg


2 Answers

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.

like image 161
Artefacto Avatar answered Sep 19 '22 14:09

Artefacto


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

like image 35
mdpatrick Avatar answered Sep 16 '22 14:09

mdpatrick