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 // )
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!