Concatenating Arrays in PHP
When trying to combine arrays, using the operator in PHP may lead to unexpected results. This is due to the way arrays are merged when using : keys are merged numerically, causing duplicates to be overwritten.
For example:
<code class="php">$array = array('Item 1'); $array += array('Item 2'); var_dump($array);</code>
The above code will output:
array(1) { [0]=> string(6) "Item 1" }
To remedy this, use array_merge() instead:
<code class="php">$arr1 = array('foo'); $arr2 = array('bar'); $combined = array_merge($arr1, $arr2);</code>
This will correctly combine the arrays into a new array:
array('foo', 'bar');
Alternatively, if the array elements have distinct keys, the operator can be used. For instance:
<code class="php">$arr1 = array('one' => 'foo'); $arr2 = array('two' => 'bar'); $combined = $arr1 + $arr2;</code>
This will create an array with both elements:
array('one' => 'foo', 'two' => 'bar');
The above is the detailed content of How to Correctly Combine Arrays in PHP to Avoid Duplicate Keys?. For more information, please follow other related articles on the PHP Chinese website!