tags:

views:

100

answers:

2

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.

+3  A: 

$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);
Gumbo
+5  A: 

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.

nickf
Thanks, I was wrong indeed.
christian studer