0

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

2 Answers 2

2

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);

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.