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
Release: 2024-11-05 15:17:02
Original
1053 people have browsed it

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>
Copy after login

"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>
Copy after login

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>
Copy after login

Expected Output:

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template