Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php array_merge associative arrays

I'm trying to prepend an item to the beginning of an associative array. I figured the best way to do this is to use array_merge, but I'm having some odd consequences. I get the id and Name of products from a mysql database, and it gets returned as an associative array, like this (not the actual data coming back, but sample data for this question that represents what the data looks like approximately):

$products = array (1 => 'Product 1', 42 => 'Product 42', 100 => 'Product 100'); 

this is getting sent to an html helper to create a dropdown that associates the key with the value, and the value of the array item gets set as the text in the drop down select control. I need the first item to be something like "Please Select" with a key of 0, so I did this:

$products = array_merge(array(0 => "Select a product" ), $products); 

The resulting array looks like this:

array(   0 => 'Select a product',    1 => 'Product 1',    2 => 'Product 42',    3 => 'Product 100'  ); 

when What I really wanted was not to lose the keys of the associative array. I was told that you can properly use array_merge with associative arrays in the manner I tried, however, I believe because my keys are ints that it is not treating the array as a true associative array, and compressing them as illustrated above.

The question is: Why is the array_merge function changing the keys of the items? can I keep it from doing this? OR is there another way for me to accomplish what I'm trying to do, to add the new item at the beginning of the array?

like image 710
stephenbayer Avatar asked Mar 08 '11 14:03

stephenbayer


People also ask

What is the difference between array_merge () and Array_merge_recursive () in PHP?

The array_merge_recursive() function merges one or more arrays into one array. The difference between this function and the array_merge() function is when two or more array elements have the same key. Instead of override the keys, the array_merge_recursive() function makes the value as an array.

How can I merge two arrays in PHP without duplicates?

You can use the PHP array_unique() function and PHP array_merge() function together to merge two arrays into one array without duplicate values in PHP.


Video Answer


1 Answers

From the docs:

If you want to append array elements from the second array to the first array while not overwriting the elements from the first array and not re-indexing, use the + array union operator

The keys from the first array argument are preserved when using the + union operator, so reversing the order of your arguments and using the union operator should do what you need:

$products = $products + array(0 => "Select a product"); 
like image 142
Mark Elliot Avatar answered Sep 28 '22 15:09

Mark Elliot