Home >Backend Development >PHP Tutorial >How to Preserve Key-Value Pairs When Merging Arrays with Duplicate Keys?
Preserving Existing Key-Value Pairs when Merging Arrays
In programming, situations arise where you need to merge two arrays while ensuring that key-value pairs from both arrays are preserved. This becomes a challenge when duplicate keys exist.
Let's consider the example provided:
<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, using the array_merge function results in the loss of the 'c' => 3 key-value pair. To address this issue, we need to employ a different approach.
The array_merge_recursive function is specifically designed for such scenarios. Unlike array_merge, it recursively merges arrays, ensuring that identical key-value pairs are preserved. The resulting array will contain both values associated with the duplicate key.
For the example given, using array_merge_recursive will produce:
<code class="php">array_merge_recursive($A, $B); // result [a] => 1 [b] => 2 [c] => [0 => 3, 1 => 4] [d] => 5</code>
As you can see, the 'c' key now contains an array with both 3 and 4 as its values. This approach allows you to merge arrays while maintaining the integrity of existing key-value relationships.
The above is the detailed content of How to Preserve Key-Value Pairs When Merging Arrays with Duplicate Keys?. For more information, please follow other related articles on the PHP Chinese website!