-4

I need to merge an associative array into another associative array. I know php's array_merge but it returns a new array. That's not what I want.

Eg

$ar1 = array('one'=>1, 'two'=>2, 'three'=>3);
$ar2 = array('four'=>4, 'five'=>5);

I want to know that is there a php function which I can use to merge $ar2 into $ar1. The result should be,

$ar1 = array('one'=>1, 'two'=>2, 'three'=>3, 'four'=>4, 'five'=>5);
Charles
  • 50,943
  • 13
  • 104
  • 142
Gihan
  • 4,163
  • 6
  • 31
  • 49
  • 2
    Can't you just use `array_merge` like this then: `$ar1 = array_merge($ar1, $ar2);` – Cyclonecode Nov 24 '12 at 05:56
  • Without using array_merge you'd have to write a loop that combines them manually. Why can't you have a new array? – Sterling Archer Nov 24 '12 at 05:58
  • @KristerAndersson Yep :). I feel shame on me. Thanks anyway – Gihan Nov 24 '12 at 06:02
  • possible duplicate of [PHP append one array to another (not array\_push or +)](http://stackoverflow.com/questions/4268871/php-append-one-array-to-another-not-array-push-or) – hakre Nov 24 '12 at 11:11

3 Answers3

2
$ar1 = array('one'=>1, 'two'=>2, 'three'=>3);
$ar2 = array('four'=>4, 'five'=>5);

use array_merge

$array3 = array_merge($ar1,$ar2);

it will merge the 2 array and store it in $array3. You can use $ar1 also.

working example http://codepad.viper-7.com/KzCHIB

Yogesh Suthar
  • 30,424
  • 18
  • 72
  • 100
0
$ar1 = array('one'=>1, 'two'=>2, 'three'=>3);
$ar2 = array('four'=>4, 'five'=>5);

$ar1 = array_merge($ar1, $ar2);

print_r($ar1);
Ravi
  • 2,078
  • 13
  • 23
0

The easiest way is to assign output of array_merge to your first array. Is this you want

<?php
$ar1 = array('one'=>1, 'two'=>2, 'three'=>3);
$ar2 = array('four'=>4, 'five'=>5);

$ar1 = array_merge($ar1,$ar2);

print_r($ar1);
?>
Pankaj Khairnar
  • 3,028
  • 3
  • 25
  • 34