Reputation: 25597
I have two sequential (non-associative) arrays whose values I want to combine into a new array, ignoring the index but preserving the order. Is there a better solution (i.e. an existing operator or function) other than do the following:
$a = array('one', 'two');
$b = array('three', 'four', 'five');
foreach($b as $value) {
$a[] = $value;
}
Remark: The '+' operator doesn't work here ('three' with index 0 overwrites 'one' with index zero). The function array_merge has the same problem.
Upvotes: 1
Views: 253
Reputation: 546005
array_merge
is what you want, and I don't think you are correct with that overwriting problem. From the manual:
If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
Upvotes: 5
Reputation: 655189
$a + $b
on two arrays is the union of $a
and $b
:
The + operator appends elements of remaining keys from the right handed array to the left handed, whereas duplicated keys are NOT overwritten.
So use array_merge
to merge both arrays:
$merged = array_merge($a, $b);
Upvotes: 3