Preserve Original Keys While Merging Numerically-Keyed Associative Arrays
When merging associative arrays with numerically-keyed elements, it's often desirable to retain the original key values. However, the array_merge function may overwrite or renumber keys when dealing with duplicate keys.
For instance, given arrays like these:
$array1 = [ '11' => '11', '22' => '22', '33' => '33', '44' => '44' ]; $array2 = [ '44' => '44', '55' => '55', '66' => '66', '77' => '77' ];
Attempting to merge these arrays using array_merge can lead to key changes:
$output = array_unique(array_merge($array1, $array2));
This approach changes the output keys to 0-based integers.
To preserve the original keys, use the following method:
$output = $array1 + $array2;
By using the addition operator ( ), PHP merges the arrays and retains the original numerical keys. The result will be:
$output = [ '11' => '11', '22' => '22', '33' => '33', '44' => '44', '55' => '55', '66' => '66', '77' => '77' ];
The above is the detailed content of How Can I Preserve Original Keys When Merging Numerically-Keyed PHP Arrays?. For more information, please follow other related articles on the PHP Chinese website!