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

How to Merge Numerically-Keyed Arrays in PHP While Preserving Original Keys?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-22 09:17:35764browse

How to Merge Numerically-Keyed Arrays in PHP While Preserving Original Keys?

Merging Numerically-Keyed Associative Arrays While Preserving Original Keys

When merging two associative arrays with numerically-keyed indices, it's common to encounter issues preserving both the elements and their original keys. Consider the following arrays:

array(
    '11' => '11',
    '22' => '22',
    '33' => '33',
    '44' => '44'
);

array(
    '44' => '44',
    '55' => '55',
    '66' => '66',
    '77' => '77'
);

Using array_unique( array_merge( $array1 , $array2 ) ) may seem like a solution, but it alters the original keys.

Solution 1: Using array_merge and array_combine

Use array_merge to combine the arrays and array_combine to recreate the original keys:

$output = array_merge($array1, $array2);
$output = array_combine($output, $output);

Solution 2: Using the Array Merge Union Operator ( )

A convenient solution is to use the array merge union operator ( ):

$output = $array1 + $array2;

Result:

In both cases, the resulting array will preserve the original keys and contain all unique elements:

array(
    '11' => '11',
    '22' => '22',
    '33' => '33',
    '44' => '44',
    '55' => '55',
    '66' => '66',
    '77' => '77'
);

The above is the detailed content of How to Merge Numerically-Keyed 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