How can make it so array_merge() overwrites two keys with different values but same key index from two arrays?
for example, merging:
[0] => 'whatever'
with
[0] => 'whatever', [1] => 'a', [2] => 'b'
should produce
[0] => 'whatever', [1] => 'a', [2] => 'b'
Basically I want array_merge to bahave the same way it behaves if the arrays have string keys...
Pretty easy to write manually:
Update: This behaves differently than the union operator (
return $first + $second;
) because in this case the second array wins when both have elements with the same key.However, if you switch the places of the arguments and place the array that you want to "win" in case of conflicts as the first operand, you can get the same behavior. So the function above behaves exactly like
return $second + $first;
.array_replace
does exactly this. See: http://php.net/manual/de/function.array-replace.phpUse the
+
operator.Compare
array_merge
to+
operator:Output:
The
+
operator still works if your associative array has the numerical keys out-of-order:Output:
Notice
array_merge
in this case creates a new key. Not desirable...Compare to WRONG use of "+"
You could use
array_merge()
and then usearray_unique()
.