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!