Imagine you have two arrays, $A and $B, and you want to merge them, preserving keys that exist in both arrays. However, you notice that when using array_merge, keys with the same name are overwritten, resulting in data loss.
To address this challenge, you must utilize array_merge_recursive instead of array_merge. This function performs a recursive merge, ensuring that keys with the same name are combined into arrays rather than overwritten.
For instance, given the following arrays:
<code class="php">$A = ['a' => 1, 'b' => 2, 'c' => 3]; $B = ['c' => 4, 'd' => 5];</code>
Merging them with array_merge_recursive would yield:
<code class="php">array_merge_recursive($A, $B); // result ['a' => 1, 'b' => 2, 'c' => [3, 4], 'd' => 5]</code>
As you can see, both values associated with key 'c' are preserved in the merged array. This method ensures that all data from both arrays is retained, eliminating the problem of missing keys.
The above is the detailed content of How Do You Merge Arrays with Duplicate Keys While Preserving All Data?. For more information, please follow other related articles on the PHP Chinese website!