I have two arrays with numeric keys. This is a small example:
$test_a = array(1 => 'one', 2 => '二');
$test_b = array(2 => 'two', 4 => 'four');
I want to merge them, with array_merge(), to receive $test_c array:
$test_c = array(
1 => 'one',
2 => 'two',
4 => 'four'
);
The manual for array_merge mentions that:
Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.
what seems to be true, because this:
$test_c = array_merge($test_a, $test_b);
var_dump($test_c);
returns:
array (size=4)
0 => string 'one' (length=3)
1 => string '二' (length=3)
2 => string 'two' (length=3)
3 => string 'four' (length=4)
What did I try:
-
I tried casting keys as strings:
foreach($test_a as $key => $value) $test_a[(string)($key)] = $value;…keys are still numeric.
-
I tried with
strval():foreach($test_a as $key => $value) $test_a[strval($key)] = $value;no change. Keys are still numeric.
-
I tried with this trick:
foreach($test_a as $key => $value) $test_a['' . $key . ''] = $value;Does not work either. The keys are still numeric.
What surprised me, was when I found out that there is something like automatic conversion from string to numeric on array keys. This changed the keys to strings:
foreach($test_a as $key => $value) $test_a[' ' . $key . ' '] = $value;
and when I added trim():
foreach($test_a as $key => $value) $test_a[trim(' ' . $key . ' ')] = $value;
the keys were converted back to numeric.
Basically, I want to merge these two arrays. I guess that the only solution is to find a way to convert the keys from numeric to string data type.
If you can additionally explain the “automatic conversion” thing then I will be fully satisfied.
You could use the
+operator on both arrays, like so:This will output:
It’s not in the exact order you’re looking for, but you could use
ksort()to sort by the keys to get the exact output. What you’re referring to as “automatic conversion” is actually called type coercion, and is referred to as type juggling in PHP.