In a piece of software, I merge two arrays with array_merge
function. But I need to add the same array (with the same keys, of course) to an existing array.
The problem:
$A = array('a' => 1, 'b' => 2, 'c' => 3); $B = array('c' => 4, 'd'=> 5); array_merge($A, $B); // result [a] => 1 [b] => 2 [c] => 4 [d] => 5
As you see, 'c' => 3
is missed.
So how can I merge all of them with the same keys?
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 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.
You need to use array_merge_recursive
instead of array_merge
. Of course there can only be one key equal to 'c'
in the array, but the associated value will be an array containing both 3
and 4
.
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