Home > Backend Development > PHP Tutorial > How do I combine two associative arrays in PHP?

How do I combine two associative arrays in PHP?

Patricia Arquette
Release: 2024-11-02 12:33:02
Original
483 people have browsed it

How do I combine two associative arrays in PHP?

Combining Associative Arrays in PHP

In PHP, combining two associative arrays into one can be achieved efficiently using the array_merge() function. Here's how you can do it:

Consider the following two associative arrays:

<code class="php">$array1 = ["name1" => "id1"];

$array2 = ["name2" => "id2", "name3" => "id3"];</code>
Copy after login

Method 1: array_merge()

To merge the arrays, use the array_merge() function as follows:

<code class="php">$array3 = array_merge($array1, $array2);</code>
Copy after login

This will create a new array $array3 that contains all the key-value pairs from both $array1 and $array2. The values for duplicate keys will be overwritten with the values from the second array.

Method 2: Array Addition ( ) Operator

Alternatively, you can use the array addition ( ) operator to merge the arrays:

<code class="php">$array4 = $array1 + $array2;</code>
Copy after login

This operator also merges the arrays, but it does not overwrite duplicate key values. Instead, it will result in a multidimensional array with duplicate keys.

Result

In both cases, $array3 and $array4 will be:

array(4) {
  ["name1"] => "id1",
  ["name2"] => "id2",
  ["name3"] => "id3"
}
Copy after login

Unit Testing

To unit test this functionality, you can create test cases that assert the expected behavior of the array_merge() function or the array addition operator. Here's an example test using PHPUnit:

<code class="php">class ArrayMergeTest extends PHPUnit_Framework_TestCase
{
    public function testArrayMerge()
    {
        $array1 = ["name1" => "id1"];
        $array2 = ["name2" => "id2", "name3" => "id3"];
        $expectedArray = ["name1" => "id1", "name2" => "id2", "name3" => "id3"];

        $actualArray = array_merge($array1, $array2);

        $this->assertEquals($expectedArray, $actualArray);
    }
}</code>
Copy after login

The above is the detailed content of How do I combine two associative arrays 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