Home > Article > Backend Development > How do I combine two 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>
Method 1: array_merge()
To merge the arrays, use the array_merge() function as follows:
<code class="php">$array3 = array_merge($array1, $array2);</code>
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>
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" }
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>
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!