Merging Associative Arrays with Preserved Numerical Keys
When combining two numerically-keyed associative arrays, it's often desired to maintain the original keys in the combined array while avoiding duplicates. Here's a simple solution:
$array1 = [ '11' => '11', '22' => '22', '33' => '33', '44' => '44', ]; $array2 = [ '44' => '44', '55' => '55', '66' => '66', '77' => '77', ]; $output = $array1 + $array2;
In PHP, the operator for arrays merges two arrays, and when two keys with the same numerical value are present, the value from the right-hand array overwrites the value from the left-hand array. However, since the keys in this case are integers, PHP treats them as numbers and renumbers the keys.
To recreate the original numerical keys, use array_combine:
$output = array_combine($output, $output);
This creates a new array with the original keys restored.
Hence, the merged array with preserved numerical keys looks like this:
[ '11' => '11', '22' => '22', '33' => '33', '44' => '44', '55' => '55', '66' => '66', '77' => '77', ]
The above is the detailed content of How Can I Merge Numerically-Keyed Associative Arrays in PHP While Preserving Original Keys?. For more information, please follow other related articles on the PHP Chinese website!