Can't concatenate 2 arrays in PHP

117,280

Solution 1

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

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

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

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

+ 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.

Share:
117,280
user3167101
Author by

user3167101

I like to make stuff. Check out my blog. You can email me at alex at my domain. My dotfiles, if you're curious :)

Updated on July 05, 2022

Comments

  • user3167101
    user3167101 almost 2 years

    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?

  • Gromski
    Gromski about 14 years
    Not the same thing. You'll get array('Item 1', array('Item 2')), a multidimensional array.
  • Josh K
    Josh K about 14 years
    Right, which is what I thought he wanted.
  • Highly Irregular
    Highly Irregular over 12 years
    Note that the array_merge function will still collapse duplicates of non-numeric array keys. eg array_merge(array("colour"=>"red"), array("colour"=>"green")) will produce the value of array("colour"=>"green);
  • JMTyler
    JMTyler about 11 years
    This is false. array_merge will only omit items from the resultant array if they are associative arrays with the same keys. For numerical arrays, all items are merged into a new array, whose length is the precise sum of the original arrays. In the example you are using numerical arrays, which means array_merge would work flawlessly for you. I agree that array_merge should not be used for associative arrays, but clearly that's not what you're showing here.
  • Nir Alfasi
    Nir Alfasi about 11 years
    @JMTyler +1 excellent comment! I should have chosen an example that uses associative arrays. The main reason I posted this answer was that the accepted answer used + which should not be used in either of the cases (associative or not) unless the keys are different. And array_merge which will contain duplicate items in case of identical items.
  • Tony
    Tony over 10 years
    “All previous answers are incorrect” is not helpful as answers are reordered depending on votes.
  • Nir Alfasi
    Nir Alfasi over 10 years
    @ChristianLescuyer it's easy to see the date/hour next to each answer.
  • Jonnix
    Jonnix almost 9 years
    That's a concat operator. You'd end up with a couple of notices and "ArrayArray".
  • xoxn-- 1'w3k4n
    xoxn-- 1'w3k4n almost 8 years
    $arr1 = array('foo'); // Same as array(0 => 'foo') $arr2 = array('bar'); // Same as array(0 => 'bar') // Will contain array('bar'); $combined = array_merge($arr1, $arr2);
  • luukvhoudt
    luukvhoudt about 4 years
    array(123 => 'foo') is the same as array("123" => 'foo') and when keys are integers they're ignored when using array_merge. Have a look at this test