1

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.

2 Answers 2

5

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.

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

Comments

3

$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);

Comments

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.