Merging Associative Arrays with Unique Keys
In PHP, associative arrays use string keys to access values. When merging two such arrays, duplicate keys can lead to the loss of original values. To avoid this, it is necessary to preserve the original keys while combining the arrays.
Consider the following example:
$array1 = [ '11' => '11', '22' => '22', '33' => '33', '44' => '44' ]; $array2 = [ '44' => '44', '55' => '55', '66' => '66', '77' => '77' ];
The goal is to merge $array1 and $array2 such that the result preserves the original keys and removes duplicates, resulting in:
$output = [ '11' => '11', '22' => '22', '33' => '33', '44' => '44', '55' => '55', '66' => '66', '77' => '77' ];
Using the array_unique function in combination with array_merge does not achieve the desired result because it reassigns keys. A more efficient approach is to use the operator, which preserves the original keys when merging arrays:
$output = $array1 + $array2;
This operation effectively combines the two arrays, overwriting duplicate values. Alternatively, to explicitly recreate the keys, the following code can be used:
$output = array_combine($output, $output);
Both methods provide a solution to the problem of merging associative arrays with unique keys while preserving the original values.
The above is the detailed content of How Can I Merge PHP Associative Arrays While Preserving Unique Keys?. For more information, please follow other related articles on the PHP Chinese website!