Home >Backend Development >PHP Tutorial >How Can I Easily Merge Two Arrays into Key-Value Pairs in PHP?
Merge Two Arrays as Key Value Pairs with Ease in PHP
Merging two arrays to create key-value pairs is a common task in PHP development. While manual looping and array manipulation may suffice, a more efficient and elegant solution exists: array_combine().
This built-in function takes two arrays as input and creates a new array with the values of the first array as keys and the values of the second array as the corresponding values. The syntax is straightforward:
$merged_array = array_combine($array_with_keys, $array_with_values);
Consider the following example:
$keys = ['apple', 'banana', 'orange']; $values = [1, 2, 3]; $merged_array = array_combine($keys, $values);
After execution, $merged_array would look like this:
Array ( [apple] => 1 [banana] => 2 [orange] => 3 )
As you can see, array_combine() seamlessly transforms the two arrays into a key-value pair structure. By leveraging its power, you can effortlessly achieve this common operation in a concise and efficient manner.
The above is the detailed content of How Can I Easily Merge Two Arrays into Key-Value Pairs in PHP?. For more information, please follow other related articles on the PHP Chinese website!