Home  >  Article  >  Backend Development  >  How to Combine Two Arrays Using `array_combine()` in PHP?

How to Combine Two Arrays Using `array_combine()` in PHP?

Linda Hamilton
Linda HamiltonOriginal
2024-11-06 01:46:02167browse

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:

  • Concise: array_combine() provides a concise one-line solution.
  • Type Safety: It verifies that the input arrays have compatible types for keys and values.

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!

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