Home > Backend Development > PHP Tutorial > How to Preserve Array Keys When Merging Arrays in PHP?

How to Preserve Array Keys When Merging Arrays in PHP?

Linda Hamilton
Release: 2024-11-15 02:12:02
Original
999 people have browsed it

How to Preserve Array Keys When Merging Arrays in PHP?

Maintaining Array Keys during Array Merging

When merging two arrays in PHP, the default array_merge function reindexes the merged array with integer keys. This behavior can be undesired, especially when the arrays contain keys that have specific string or integer values.

To preserve the original array keys during merging, you can use the array addition ( ) operator. This operator appends the second array to the first array while maintaining the keys from both arrays. For example:

$array1 = array(1, 2, 3); // Integer keys
$array2 = array("a" => 1, "b" => 2, "c" => 3); // String keys
$mergedArray = $array1 + $array2;

// Print the merged array
print_r($mergedArray);

// Expected Output:
// Array (
//   [0] => 1
//   [1] => 2
//   [2] => 3
//   [a] => 1
//   [b] => 2
//   [c] => 3
// )
Copy after login

In this example, the integer keys from $array1 and the string keys from $array2 are both preserved in the merged array. This approach is particularly useful when you want to combine arrays with different key types or when you need to preserve specific key values.

The above is the detailed content of How to Preserve Array Keys When Merging Arrays in PHP?. 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