Home > Backend Development > PHP Tutorial > How Can I Merge Numeric Arrays in PHP While Preserving Original Keys?

How Can I Merge Numeric Arrays in PHP While Preserving Original Keys?

Susan Sarandon
Release: 2025-01-04 14:22:40
Original
536 people have browsed it

How Can I Merge Numeric Arrays in PHP While Preserving Original Keys?

Merging Numeric Arrays with Preserved Keys

Often, we encounter the need to combine two arrays without introducing duplicates or altering their original keys. To achieve this, let's explore the various methods available in PHP.

Using array_merge:

The array_merge() function provides a straightforward way to combine two arrays. By default, it overwrites duplicate keys with the values from the latter array. In this case, since the arrays have string keys, which are treated as integers in PHP, the keys get renumbered. To preserve the original keys, we can use:

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

Using array_combine:

If the keys are crucial, we can utilize array_combine() to recreate the array with the desired keys. The syntax is:

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

Using the ' ' Operator:

Another elegant solution is to use the ' ' operator, which natively merges arrays and preserves their keys. This is the recommended method:

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

Example:

Consider the example arrays:

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

$array2 = array(
'44' => '44',
'55' => '55',
'66' => '66',
'77' => '77'
);
Copy after login

Using the suggested methods, we can obtain the following output:

$output = array(
'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 Merge Numeric Arrays in PHP While Preserving Original 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