Home >Backend Development >PHP Tutorial >How Can I Preserve Original Keys When Merging Numerically-Keyed PHP Arrays?

How Can I Preserve Original Keys When Merging Numerically-Keyed PHP Arrays?

Linda Hamilton
Linda HamiltonOriginal
2024-12-13 21:31:26825browse

How Can I Preserve Original Keys When Merging Numerically-Keyed PHP Arrays?

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!

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