Home > Article > Backend Development > How to Combine Two Arrays Using `array_combine()` in PHP?
Combining Two Arrays with array_combine()
To efficiently map the values of one array as the keys of another, consider utilizing the built-in array_combine() function. It takes two arrays as arguments. The first array specifies the keys, and the second array contains the corresponding values.
Example:
Given two arrays, 'A' and 'B', let's demonstrate how to combine them:
<code class="php">$array['A'] = ['cat', 'bat', 'hat', 'mat']; $array['B'] = ['fur', 'ball', 'clothes', 'home'];</code>
Expected Output:
<code class="php">$array['C'] = [ 'cat' => 'fur', 'bat' => 'ball', 'hat' => 'clothes', 'mat' => 'home', ];</code>
Code:
<code class="php">$array['C'] = array_combine($array['A'], $array['B']);</code>
Advantages:
Alternatives:
You can also use loops to accomplish this task, but array_combine() offers the most efficient and readable approach.
The above is the detailed content of How to Combine Two Arrays Using `array_combine()` in PHP?. For more information, please follow other related articles on the PHP Chinese website!