0

I have some problems during working with arrays using the array_merge function. Here's an example:

$first_array = [
    8 => [
        'name' => "Hershey's Chocolate Milk Shake",
        'code' => 8 ,
        'price' => 29.00,
        'quantity' => 1,
        'image' => "Hersheys_Chocolate_Milk_Shake.jpg",
        'percentage_discount' => 0,
        'offer_mrp' => 0,
    ]
];
$second_array = [
    20 => [
        'name' => 'Kissan Mixed Fruit Jam 700g',
        'code' => 20,
        'price' => 215.00,
        'quantity' => 1,
        'image' => 'Kissan Mixed Fruit Jam 700g.jpg',
        'percentage_discount' => 0,
        'offer_mrp' => 0 
    ]
];

$first_array = array_merge($first_array, $second_array); 
print_r($first_array);

The result is:

Array ( 
    [0] => Array ( 
        [name] => Hershey's Chocolate Milk Shake 
        [code] => 8 
        [price] => 29.00 
        [quantity] => 1 
        [image] => Hersheys_Chocolate_Milk_Shake.jpg 
        [percentage_discount] => 0 
        [offer_mrp] => 0
    ) 
    [1] => Array ( 
        [name] => Kissan Mixed Fruit Jam 700g 
        [code] => 20 
        [price] => 215.00 
        [quantity] => 1 
        [image] => Kissan Mixed Fruit Jam 700g.jpg 
        [percentage_discount] => 0 [offer_mrp] => 0 
    ) 
);

But I want it to be:

Array ( 
    [8] => Array ( 
        [name] => Hershey's Chocolate Milk Shake 
        [code] => 8 
        [price] => 29.00 
        [quantity] => 1 
        [image] => Hersheys_Chocolate_Milk_Shake.jpg 
        [percentage_discount] => 0 
        [offer_mrp] => 0
    ) 
    [20] => Array ( 
        [name] => Kissan Mixed Fruit Jam 700g 
        [code] => 20 
        [price] => 215.00 
        [quantity] => 1 
        [image] => Kissan Mixed Fruit Jam 700g.jpg 
        [percentage_discount] => 0 [offer_mrp] => 0 
    )
)
4
  • Just use simple +, it doesn't overwrite keys. Commented May 8, 2020 at 10:42
  • 1
    Can you please use formatting? and if possible please echo/print your variables like this, because it's unreadable: echo '<pre>' . print_r($first_array, true) . '</pre>'; Commented May 8, 2020 at 10:44
  • @u_mulder array_merge() do not over-write keys.. Commented May 8, 2020 at 10:46
  • Thanks for your solution and it is done using + operator Commented May 8, 2020 at 11:20

1 Answer 1

1

array_merge() renumerates numeric keys. You should use operator + instead.

$first_array = $first_array + $second_array;

Output is exactly the same as you want.

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

2 Comments

Thank you so much for solution and it is run successfully.
@Manish Please mark answer as correct if it resolved your question.

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.