Home >Backend Development >PHP Tutorial >How Can PHP's `array_combine()` Function Merge Two Arrays into a Key-Value Pair Array?

How Can PHP's `array_combine()` Function Merge Two Arrays into a Key-Value Pair Array?

DDD
DDDOriginal
2024-12-13 17:21:10936browse

How Can PHP's `array_combine()` Function Merge Two Arrays into a Key-Value Pair Array?

Merge Arrays into Key-Value Pairs with PHP

Combining two arrays into a single key-value pair array is a common task in programming. While a manual approach may suffice, there's an elegant solution using PHP's array_combine() function.

Problem Statement:

You have two arrays of equal length, and you need to merge them such that the values of the first array become the keys in the merged array, while the values of the second array become the corresponding values in the merged array.

Solution using array_combine():

PHP's array_combine() function takes two arrays as arguments and returns a new array with the keys from the first array and the values from the second array. This perfectly suits our requirement.

The syntax of array_combine() is as follows:

array_combine(array $keys, array $values)

In your case, where $array_with_keys contains the keys and $array_with_values contains the values, you can use the following code:

$mapped_array = array_combine($array_with_keys, $array_with_values);

This will create a new array $mapped_array, where $array_with_keys becomes the key index and $array_with_values becomes the corresponding value.

Example:

Consider the following arrays:

$array_with_keys = ['key1', 'key2', 'key3'];
$array_with_values = [1, 2, 3];

Using array_combine(), you can merge them into the following key-value pair array:

$mapped_array = array_combine($array_with_keys, $array_with_values);

// $mapped_array will be:
// ['key1' => 1, 'key2' => 2, 'key3' => 3]

The above is the detailed content of How Can PHP's `array_combine()` Function Merge Two Arrays into a Key-Value Pair Array?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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