Can't concatenate 2 arrays in PHP Can't concatenate 2 arrays in PHP arrays arrays

Can't concatenate 2 arrays in PHP


Both will have a key of 0, and that method of combining the arrays will collapse duplicates. Try using array_merge() instead.

$arr1 = array('foo'); // Same as array(0 => 'foo')$arr2 = array('bar'); // Same as array(0 => 'bar')// Will contain array('foo', 'bar');$combined = array_merge($arr1, $arr2);

If the elements in your array used different keys, the + operator would be more appropriate.

$arr1 = array('one' => 'foo');$arr2 = array('two' => 'bar');// Will contain array('one' => 'foo', 'two' => 'bar');$combined = $arr1 + $arr2;

Edit: Added a code snippet to clarify


Use array_merge()
See the documentation here:
http://php.net/manual/en/function.array-merge.php

Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.


IMO some of the previous answers are incorrect!(It's possible to sort the answers to start from oldest to newest).

array_merge() actually merges the arrays, meaning, if the arrays have a common item one of the copies will be omitted. Same goes for + (union).

I didn't find a "work-around" for this issue, but to do it manually...

Here it goes:

<?php$part1 = array(1,2,3);echo "array 1 = \n";print_r($part1);$part2 = array(4,5,6);echo "array 2 = \n";print_r($part2);$ans = NULL;for ($i = 0; $i < count($part1); $i++) {    $ans[] = $part1[$i];}for ($i = 0; $i < count($part2); $i++) {    $ans[] = $part2[$i];}echo "after arrays concatenation:\n";print_r($ans);?>