Home > Backend Development > PHP Tutorial > How Can I Merge PHP Associative Arrays While Preserving Unique Keys?

How Can I Merge PHP Associative Arrays While Preserving Unique Keys?

Patricia Arquette
Release: 2024-12-17 18:15:20
Original
303 people have browsed it

How Can I Merge PHP Associative Arrays While Preserving Unique Keys?

Merging Associative Arrays with Unique Keys

In PHP, associative arrays use string keys to access values. When merging two such arrays, duplicate keys can lead to the loss of original values. To avoid this, it is necessary to preserve the original keys while combining the arrays.

Consider the following example:

$array1 = [
    '11' => '11',
    '22' => '22',
    '33' => '33',
    '44' => '44'
];

$array2 = [
    '44' => '44',
    '55' => '55',
    '66' => '66',
    '77' => '77'
];
Copy after login

The goal is to merge $array1 and $array2 such that the result preserves the original keys and removes duplicates, resulting in:

$output = [
    '11' => '11',
    '22' => '22',
    '33' => '33',
    '44' => '44',
    '55' => '55',
    '66' => '66',
    '77' => '77'
];
Copy after login

Using the array_unique function in combination with array_merge does not achieve the desired result because it reassigns keys. A more efficient approach is to use the operator, which preserves the original keys when merging arrays:

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

This operation effectively combines the two arrays, overwriting duplicate values. Alternatively, to explicitly recreate the keys, the following code can be used:

$output = array_combine($output, $output);
Copy after login

Both methods provide a solution to the problem of merging associative arrays with unique keys while preserving the original values.

The above is the detailed content of How Can I Merge PHP Associative Arrays While Preserving Unique Keys?. 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