Combine Two Arrays with numerical keys without overwriting the old keys

array_merge() appends the values of the second array to the first. It does not overwrite keys.

Your example, results in:

Array ( [0] => foo [1] => bar [2] => bar [3] => foo )

However, If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.

Unless this was just an example to another problem you were having?


Does this answer your question? I'm not sure exactly what you're trying to accomplish, but from your description it sounds like this will work:

$array1 = array(0=>'foo', 1=>'bar');
$array2 = array(0=>'bar', 1=>'foo');

foreach ($array2 as $i) {
    $array1[] = $i;
}

echo var_dump($array1);

Tags:

Php

Arrays