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
Release: 2024-12-13 21:31:26
Original
827 people have browsed it

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'
];
Copy after login

Attempting to merge these arrays using array_merge can lead to key changes:

$output = array_unique(array_merge($array1, $array2));
Copy after login

This approach changes the output keys to 0-based integers.

To preserve the original keys, use the following method:

$output = $array1 + $array2;
Copy after login

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'
];
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template