Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't concatenate 2 arrays in PHP

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?

like image 468
alex Avatar asked Apr 16 '10 02:04

alex


People also ask

How can I merge two arrays in PHP?

The array_merge() is a builtin function in PHP and is used to merge two or more arrays into a single array. This function is used to merge the elements or values of two or more arrays together into a single array.

What is the difference between array_merge () and Array_merge_recursive () in PHP?

The array_merge_recursive() function merges one or more arrays into one array. The difference between this function and the array_merge() function is when two or more array elements have the same key. Instead of override the keys, the array_merge_recursive() function makes the value as an array.

How do I combine two arrays?

To merge elements from one array to another, we must first iterate(loop) through all the array elements. In the loop, we will retrieve each element from an array and insert(using the array push() method) to another array. Now, we can call the merge() function and pass two arrays as the arguments for merging.

How can I append an array to another array in PHP?

Given two array arr1 and arr2 and the task is to append one array to another array. Using array_merge function: This function returns a new array after merging the two arrays. $arr1 = array ( "Geeks" , "g4g" );


2 Answers

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

like image 199
awgy Avatar answered Sep 17 '22 13:09

awgy


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.

like image 36
Christopher Altman Avatar answered Sep 18 '22 13:09

Christopher Altman