Home >Backend Development >PHP Tutorial >How to Merge Arrays with Identical Keys and Preserve All Data?
Merging Arrays with Identical Keys: Overcoming the Limitations of array_merge
In software development, merging arrays with identical keys can be a common task. However, the array_merge function often fails to combine all elements with the same keys, resulting in data loss.
Consider the following example:
<code class="php">$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</code>
As demonstrated, the original value of 'c' => 3 is lost after merging. To address this issue, an alternative approach is required.
Solution: array_merge_recursive
The solution lies in using the array_merge_recursive function instead. Unlike array_merge, array_merge_recursive recursively merges the keys and values of the input arrays, preserving all data.
The following code demonstrates this approach:
<code class="php">$A = array('a' => 1, 'b' => 2, 'c' => 3); $B = array('c' => 4, 'd' => 5); array_merge_recursive($A, $B); // Result [a] => 1 [b] => 2 [c] => [0 => 3, 1 => 4] [d] => 5</code>
As you can see, both values associated with 'c' are retained. However, since there can only be one 'c' key in the merged array, the result becomes an array within an array.
The above is the detailed content of How to Merge Arrays with Identical Keys and Preserve All Data?. For more information, please follow other related articles on the PHP Chinese website!