Can't concatenate 2 arrays in PHP

PhpArraysConcatenation

Php Problem Overview


I've recently learned how to join 2 arrays using the + operator in PHP.

But consider this code...

$array = array('Item 1');

$array += array('Item 2');

var_dump($array);

Output is

> array(1) { [0]=> string(6) "Item > 1" }

Why does this not work? Skipping the shorthand and using $array = $array + array('Item 2') does not work either. Does it have something to do with the keys?

Php Solutions


Solution 1 - 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

Solution 2 - Php

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.

Solution 3 - Php

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);
?>

Solution 4 - Php

use the splat ( or spread ) operator:

  $animals = ['dog', 'cat', 'snake', 'pig', 'chicken'];
  $fruits = ['apple', 'banana', 'water melon'];
  $things = [...$animals, ...$fruits];

source: https://www.kindacode.com/article/merging-arrays-in-php-7/

Solution 5 - Php

+ is called the Union operator, which differs from a Concatenation operator (PHP doesn't have one for arrays). The description clearly says:

> The + operator appends elements of remaining keys from the right handed array to the left handed, whereas duplicated keys are NOT overwritten.

With the example:

$a = array("a" => "apple", "b" => "banana");
$b = array("a" => "pear", "b" => "strawberry", "c" => "cherry");
$c = $a + $b;

array(3) {
  ["a"]=>
  string(5) "apple"
  ["b"]=>
  string(6) "banana"
  ["c"]=>
  string(6) "cherry"
}

Since both your arrays have one entry with the key 0, the result is expected.

To concatenate, use array_merge.

Solution 6 - Php

Try array_merge.

$array1 = array('Item 1');

$array2 = array('Item 2');

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

I think its because you are not assigning a key to either, so they both have key of 0, and the + does not re-index, so its trying to over write it.

Solution 7 - Php

It is indeed a key conflict. When concatenating arrays, duplicate keys are not overwritten.

Instead you must use array_merge()

$array = array_merge(array('Item 1'), array('Item 2'));

Solution 8 - Php

$array = array('Item 1');

array_push($array,'Item 2');

or

$array[] = 'Item 2';

Solution 9 - Php

This works for non-associative arrays:

while(($item = array_shift($array2)) !== null && array_push($array1, $item));

Solution 10 - Php

Try saying

$array[] = array('Item 2'); 

Although it looks like you're trying to add an array into an array, thus $array[][] but that's not what your title suggests.

Solution 11 - Php

you may use operator . $array3 = $array1.$array2;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionalexView Question on Stackoverflow
Solution 1 - PhpawgyView Answer on Stackoverflow
Solution 2 - PhpChristopher AltmanView Answer on Stackoverflow
Solution 3 - PhpNir AlfasiView Answer on Stackoverflow
Solution 4 - PhpSergio A. KesslerView Answer on Stackoverflow
Solution 5 - PhpdecezeView Answer on Stackoverflow
Solution 6 - PhpRabbottView Answer on Stackoverflow
Solution 7 - PhpRupert Madden-AbbottView Answer on Stackoverflow
Solution 8 - PhpBrant MessengerView Answer on Stackoverflow
Solution 9 - PhpHenryView Answer on Stackoverflow
Solution 10 - PhpJosh KView Answer on Stackoverflow
Solution 11 - PhprandomWalkView Answer on Stackoverflow