I use array_merge function for merging two arrays. In most case it works properly
$x = array_merge(array('a' => 'x', 'b' => 'x'), array('b' => 'y', 'c' => 'y'));
var_dump($x);
// array(3) { ["a"]=> string(1) "x" ["b"]=> string(1) "y" ["c"]=> string(1) "y" }
But for numeric case it returns unexpected result
$x = array_merge(array('1' => 'x', '2' => 'x'), array('2' => 'y', '3' => 'y'));
var_dump($x);
// array(4) { [0]=> string(1) "x" [1]=> string(1) "x" [2]=> string(1) "y" [3]=> string(1) "y" }
How to prevent renumbering of indexes? There is way to merge two arrays by base php functions without renumbering of numeric indexes?
from the manual:
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.
so, instead use array_replace.
If you want to append array elements from the second array to the first array while not overwriting the elements from the first array and not re-indexing, use the + array union operator:
<?php
$array1 = array(0 => 'zero_a', 2 => 'two_a', 3 => 'three_a');
$array2 = array(1 => 'one_b', 3 => 'three_b', 4 => 'four_b');
$result = $array1 + $array2;
var_dump($result);
?>
The keys from the first array will be preserved. If an array key exists in both arrays, then the element from the first array will be used and the matching key's element from the second array will be ignored.
array(5) {
[0]=>
string(6) "zero_a"
[2]=>
string(5) "two_a"
[3]=>
string(7) "three_a"
[1]=>
string(5) "one_b"
[4]=>
string(6) "four_b"
}
You can use array_replace()
for that:
$x = array_replace(array('1' => 'x', '2' => 'x'), array('2' => 'y', '3' => 'y'));
var_dump($x);
Output:
array(3) {
[1]=>
string(1) "x"
[2]=>
string(1) "y"
[3]=>
string(1) "y"
}