Skip to content
Advertisement

php array_merge_recursive is replacing some key strings with numeric keys

I am experiencing unexpected behaviour with the php function array_merge_recursive. Any advice or work-around would be appreciated.

The problem is with unexpected replacement of string keys with numeric key during the array_merge_recursive.

Details:

I have three associative arrays ($birthdays,$custom,$natHolidays), to which these values are programmatically added:

JavaScript

I then merge the arrays: $dates = array_merge_recursive($birthdays,$custom,$natHolidays);

The resulting $dates array outputs:

JavaScript

The only pattern I have noticed is that any key string starting with a '0' (i.e. 0130) works as expected, and any key string starting with a '1' (i.e. 1022) replaces the string key with a sequential numeric key.

Thoughts?

Btw:

Creating the new tag ‘array-merge-recursive’ requires at least 1500 reputation. Try something from the existing tags list instead.

Advertisement

Answer

PHP is loosely typed, and it is casting your array keys.

You could use integer as keys to avoid the cast:

JavaScript

and not

JavaScript

Updated answer:

The casting is treating keys starting with “0” as strings, and so far so good. The other keys are treated like integers, and array_merge will renumber them starting from 0 (as it is happening here).

I know you are using array_merge_recursive, but it appears to behave the same.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement