Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does array_merge preserve order?

Tags:

php

I have two arrays :

$arr = ["ham", "beef", "testing1"];
$arr1 = ["baby", "chicken", "wax"];

When merging them I get the following result :

var_dump(array_merge($arr, $arr1));
// ["ham", "beef", "testing1", "baby", "chicken", "wax"]

As you can see, the order is kept and they're added at the end of the first array. Can I be SURE that this is ALWAYS the case? Or the order is not necessarily kept? I found nothing in the docs about the order of the results.

like image 421
Alexandre Elshobokshy Avatar asked Sep 05 '25 03:09

Alexandre Elshobokshy


1 Answers

You can read more in documentation:

Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.

So as you can see the values of second array are appended to the end of the previous one.

For duplicate keys the last one will override the previous one as it states in documentation:

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.

like image 72
Edison Biba Avatar answered Sep 08 '25 00:09

Edison Biba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!