Home >Backend Development >PHP Tutorial >How Can I Merge Numerically-Keyed Associative Arrays in PHP While Preserving Original Keys?

How Can I Merge Numerically-Keyed Associative Arrays in PHP While Preserving Original Keys?

Barbara Streisand
Barbara StreisandOriginal
2024-12-16 17:05:22701browse

How Can I Merge Numerically-Keyed Associative Arrays in PHP While Preserving Original Keys?

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!

Statement:
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