Sunday 1 September 2013

merge arrays without reindexing keys

merge arrays without reindexing keys

I have two arrays that I want to merge recursively, so adding arrays is
not an option. This is simple example without multilevels to demonstrate
the problem:
$a1 = Array(
5 => 'pronoun'
)
$a2 = Array(
2 => 'verb',
3 => 'noun'
)
$r = array_merge_recursive($a1, $a2)
And I want to get that resulting array:
Array(
5 => 'pronoun'
2 => 'verb',
3 => 'noun'
)
My problem is that array_merge_recursive function reindixes keys, and I
get the following:
Array(
0 => 'pronoun'
1 => 'verb',
2 => 'noun'
)
I understand that's happening because all my keys are numeric. So I tried
to make them string when adding but it doesn't seem to be working
properly:
$a1[(string)7] = 'some value';
The key - 7 - is still number, or at least that's how it is displayed in
debugger - $a1[7] and not $a1['7']. Any advice?

No comments:

Post a Comment