Search code examples
phparraysmultidimensional-arraydynamic-arrays

Merging two assosiative arrays in php?


I have two associative arrays.

array ( [apple]=>1 [banana]=>2 cocunet => 3)

and other array is

array ( [apple]=>2 [banana]=>3 cocunet => 4)

now i want to merge my array like that

array ( [apple]=>1,2 [banana]=>2,3 cocunet => 3,4)

Solution

  • There is no such array in PHP. The thing you want can only be done by creating multidimentional arrays.

    $a1 = array( 'apple'=>1,'banana'=>2,'coconut'=> 3);
    
    $a2 = array( 'apple'=>2,'banana'=>3,'coconut'=> 4);
    
    echo "<pre>";
    print_r(array_merge_recursive($a1,$a2));
    echo "</pre>";
    

    For this you can use the array_merge_recursive() function.

    PHPFiddle: http://3v4l.org/5OCKI