4

Suppose I have an associative array with keys that are alphabetic string, and if I merge something to this array, It will merge successfully without reindexing like

$arr1 = array('john'=>'JOHN', 'marry'=>'Marry');
$arr1 = array_merge(array('78'=>'Angela'),$arr1);
print_r($arr1);

then this will correctly merge new component to array and its output will be

Array
(
    [0] => Angela
    [john] => JOHN
    [marry] => Marry
)

But when I tried same thing like this

 $arr1 = array('34'=>'JOHN', '04'=>'Marry');
 $arr1 = array_merge(array('78'=>'Angela'),$arr1);
 print_r($arr1);

then its output is like this

Array
(
    [0] => Angela
    [1] => JOHN
    [04] => Marry
)

Can anyone describes this scenario..... Also I want my array to be like this after merging..

Array
    (
        [78] => Angela
        [34] => JOHN
        [04] => Marry
    )

How can I Achieve that??

SNishant
  • 103
  • 11

2 Answers2

2

as per definition array_merge will reindex numeric indexes. a string with a numeric value is also a numeric index.

To prevent this behaviour concatenate the arrays using $arr1+$arr2

Claudio Pinto
  • 389
  • 2
  • 9
1

You don't need to use array_merge() as you can simply add the arrays:

$arr1 = [
  '10' => 'Angela',
  'john' => 'JOHN',
  'marry' => 'Marry',
];

$arr2 = [
  '78' => 'Angela'
];

$arr3 = $arr2 + $arr1;

array_merge() - ... values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.

Ilia Ross
  • 13,086
  • 11
  • 53
  • 88