kashfiq
kashfiq

Reputation: 43

Associative Array merge in php

I want to merge array in php. Here I pushed array value to a master array. Here my master array is

$master_array = [
  56 => [
    'item_name'=> 'xyz',
    'item_code'=> 56,
  ]
];

sub array which I want to push

$sub_array = [
  60 => [
    'item_name'=> 'xy',
    'item_code'=> 60,
  ]
];

And finally array should be

$array = [
  56 => [
    'item_name'=> 'xyz',
    'item_code'=> 56,
  ],
  60 => [
    'item_name'=> 'xy',
    'item_code'=> 60,
  ]
];

I tried with

array_push( $master_array , $sub_array );

But it's always replacing

Upvotes: 0

Views: 61

Answers (2)

Subhashis Pandey
Subhashis Pandey

Reputation: 1538

Use php function array_merge()

$master_array = [
  56 => [
    'item_name'=> 'xyz',
    'item_code'=> 56,
  ]
];

$sub_array = [
  60 => [
    'item_name'=> 'xy',
    'item_code'=> 60,
  ]
];

$array = array_merge($master_array , $sub_array);

Upvotes: 2

Tuan Dao
Tuan Dao

Reputation: 2805

You can use + operator: $array = $master_array + $sub_array;

$master_array = [
  56 => [
    'item_name'=> 'xyz',
    'item_code'=> 56,
  ]
];

$sub_array = [
  60 => [
    'item_name'=> 'xy',
    'item_code'=> 60,
  ]
];

$array = $master_array + $sub_array;

print_r($array);

The result will be:

Result

Upvotes: 1

Related Questions