I had a head-scratcher yesterday.
Basically I had an associative array of some data with string keys(containing numeric values, but still, quoted strings) to go in a <select> box as options. I wanted to prepend a placeholder value to the select box’s options.
I attempted to use array_merge:
$placeholder = "Month";
$source = array
(
'01' => '01 - January',
'02' => '02 - February',
'03' => '03 - March',
'04' => '04 - April',
'05' => '05 - May',
'06' => '06 - June',
'07' => '07 - July',
'08' => '08 - August',
'09' => '09 - September',
'10' => '10 - October',
'11' => '11 - November',
'12' => '12 - December'
);
$source = array_merge(array('' => $placeholder), $source);
And I was seeing weird results — the resultant $source array was similar to the following:
(
'' => 'Month',
'01' => '01 - January',
'02' => '02 - February',
'03' => '03 - March',
'04' => '04 - April',
'05' => '05 - May',
'06' => '06 - June',
'07' => '07 - July',
'08' => '08 - August',
'09' => '09 - September',
0 => '10 - October',
1 => '11 - November',
2 => '12 - December'
);
Note that it began using what appear to be auto-incrementing integer keys for October through December for some reason.
I can replace the array_merge call with this:
$source = array('' => $placeholder) + $source;
And the array doesn’t get rekeyed and everything is fine, but I don’t understand what’s happening under the scenes in the array_merge case.
Can anyone please explain what was happening to my array keys when I used array_merge? Thanks!
Problem doesn’t come from the
array_merge()function.If you print
$sourcebefore merging, you’ll have this :Try to rename your first key
'01'to'1', You will have the following return :PHP auto convert your key to integer. But I can’t say you why It does it.
EDIT :
I have found the answer on php.net (PHP.net) :