In PHP, use the array_combine() function to merge two arrays and retain the key-value correspondence. The syntax is: array_combine(array $keys, array $values). The first parameter is the key value array, and the second parameter is the value array.
Merge arrays in PHP and retain key-value correspondence
Preface
In PHP, when merging arrays, we can use thearray_merge()
function or theoperator. However, these methods cannot preserve the key-value correspondence of array elements. This article will introduce a method to merge arrays while retaining key-value correspondence.
Method
You can use thearray_combine()
function to merge arrays while retaining the key-value correspondence. The function takes two parameters: an array for the keys and another for the values. The syntax is as follows:
array_combine(array $keys, array $values);
Practical case
Consider the following two arrays:
$keys = ['a', 'b', 'c']; $values = [1, 2, 3];
To merge these arrays and retain the key-value correspondence, you can use The following code:
$mergedArray = array_combine($keys, $values); print_r($mergedArray);
Output
Array ( [a] => 1 [b] => 2 [c] => 3 )
As you can see, the merged array contains the key-value correspondence of the original array.
The above is the detailed content of After merging PHP arrays, how to retain the key-value correspondence?. For more information, please follow other related articles on the PHP Chinese website!