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

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

Linda Hamilton
Release: 2024-11-06 01:46:02
Original
280 people have browsed it

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

Expected Output:

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

Code:

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

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!

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