Home > Article > Backend Development > How do you combine associative arrays in PHP while preserving their key-value structure?
Combining associative arrays can be a common task in PHP. To achieve this, multiple options are available, each with its own advantages and limitations. Let's explore two popular methods:
array_merge() is a built-in PHP function that efficiently combines multiple arrays into a single array. It appends the values of the subsequent arrays to the first array.
<code class="php">$array1 = array("name1" => "id1"); $array2 = array("name2" => "id2", "name3" => "id3"); $array3 = array_merge($array1, $array2);</code>
In this example, $array3 will be an associative array that includes both key-value pairs from $array1 and $array2.
PHP also allows you to add arrays using the addition operator ( ). However, this method treats the arrays as simple arrays and the resulting array will lose the associative nature.
<code class="php">$array1 = array("name1" => "id1"); $array2 = array("name2" => "id2", "name3" => "id3"); $array4 = $array1 + $array2;</code>
In this case, $array4 will be a simple array with the values "id1", "id2", and "id3".
To unit test your code, you can create test cases with different array configurations and assert the expected output. Here's an example:
<code class="php">class ArrayMergeTest extends PHPUnit\Framework\TestCase { public function testArrayMerge() { $array1 = array("name1" => "id1"); $array2 = array("name2" => "id2", "name3" => "id3"); $expected = array("name1" => "id1", "name2" => "id2", "name3" => "id3"); $result = array_merge($array1, $array2); $this->assertEquals($expected, $result); } }</code>
The above is the detailed content of How do you combine associative arrays in PHP while preserving their key-value structure?. For more information, please follow other related articles on the PHP Chinese website!