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."
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With