Home > Article > Backend Development > How to Merge Arrays with Matching Keys Without Losing Data?
Merging Arrays with Matching Keys Recursively
In software development, it's common to combine arrays to consolidate data. However, merging arrays with identical keys can pose a challenge. The array_merge() function merges arrays by overwriting values with the same key, potentially losing data.
Consider the following example:
$A = ['a' => 1, 'b' => 2, 'c' => 3]; $B = ['c' => 4, 'd' => 5]; array_merge($A, $B); // Result: ['a'] => 1 ['b'] => 2 ['c'] => 4 ['d'] => 5
As you can see, the value for key 'c' is overwritten, resulting in the loss of the value 3. To address this issue, you can use the array_merge_recursive() function instead.
$A = ['a' => 1, 'b' => 2, 'c' => 3]; $B = ['c' => 4, 'd' => 5]; array_merge_recursive($A, $B); // Result: ['a'] => 1 ['b'] => 2 ['c'] => [3, 4] ['d'] => 5
array_merge_recursive() merges arrays recursively, combining values with the same key into an array. In this case, the resulting array contains all values associated with key 'c' ([3, 4]). This ensures that no data is lost when merging arrays with matching keys.
The above is the detailed content of How to Merge Arrays with Matching Keys Without Losing Data?. For more information, please follow other related articles on the PHP Chinese website!