How to Preserve Key-Value Pairs When Merging Arrays with Duplicate Keys?

Barbara Streisand
Release: 2024-11-02 23:32:29
Original
870 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template