Home >Backend Development >PHP Tutorial >How Can You Combine Two Arrays with Key-Value Pairs Using `array_combine()`?

How Can You Combine Two Arrays with Key-Value Pairs Using `array_combine()`?

Linda Hamilton
Linda HamiltonOriginal
2024-11-05 15:17:021109browse

How Can You Combine Two Arrays with Key-Value Pairs Using `array_combine()`?

Utilizing array_combine() to Merge Key-Value Arrays

The challenge of combining two arrays, assigning the values of one as keys for the other, can be effectively addressed using the array_combine() function. As suggested by the manual:

<code class="php">array array_combine(array $keys, array $values)</code>

"Creates an array by using the values from the keys array as keys and the values from the values array as the corresponding values."

Example:

Given the following arrays:

<code class="php">$array['A'] = ['cat', 'bat', 'hat', 'mat'];
$array['B'] = ['fur', 'ball', 'clothes', 'home'];</code>

To create an array C where A's values become keys and B's values become the associated values:

<code class="php">$array['C'] = array_combine($array['A'], $array['B']);</code>

Expected Output:

<code class="php">$array['C'] = [
    'cat' => 'fur',
    'bat' => 'ball',
    'hat' => 'clothes',
    'mat' => 'home',
];</code>

While other methods involving loops can achieve the same result, array_combine() provides a straightforward and concise solution for this specific task.

The above is the detailed content of How Can You Combine Two Arrays with Key-Value Pairs Using `array_combine()`?. 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