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?
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.
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.
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.
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" );
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With