Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

merge two arrays, while maintaining the numeric keys

Tags:

arrays

php

im trying to merge two arrays together. both have numeric keys and are unique. when i use array_merge, it re-indexes starting at 0.

so lets say i have

[2] = abc
[5] = cde

and i have

[32] = fge
[13] = def

i want to merge these two together maintaining the unique keys.

below is the explaination on the current merge behavior.. any way around this?

"If all of the arrays contain only numeric keys, the resulting array is given incrementing keys starting from zero."

like image 975
Roeland Avatar asked Aug 03 '10 02:08

Roeland


People also ask

How do I combine two arrays?

To merge elements from one array to another, we must first iterate(loop) through all the array elements. In the loop, we will retrieve each element from an array and insert(using the array push() method) to another array. Now, we can call the merge() function and pass two arrays as the arguments for merging.

Which function is used to merge two arrays?

The array_merge() function merges one or more arrays into one array. Tip: You can assign one array to the function, or as many as you like. Note: If two or more array elements have the same key, the last one overrides the others.

How do I combine two arrays into a new array?

The concat() method concatenates (joins) two or more arrays. The concat() method returns a new array, containing the joined arrays. The concat() method does not change the existing arrays.

Which function combines for merge two or more arrays?

array_merge() Function: The array_merge() function is used to merge two or more arrays into a single array. This function is used to merge the elements or values of two or more arrays together into a single array.


1 Answers

Try using the + operator.

$one = array(2 => 'abc', 5 => 'cde');
$two = array(32 => 'fge', 13 => 'def');
$three = $one + $two;

$three should now look like this:

[2] = abc
[5] = cde
[32] = fge
[13] = def
like image 146
Matt Huggins Avatar answered Sep 18 '22 18:09

Matt Huggins