PHP append one array to another (not array_push or +)
At the end it should be: Array( [0]=>a [1]=>b [2]=>c [3]=>d ) If I use something like [] or array_push , it will cause one of these results:
Array( [0]=>a [1]=>b [2]=>Array( [0]=>c [1]=>d ) ) //or Array( [0]=>c [1]=>d )
foreach ( $b AS $var ) $a[] = $var;
none of the outputs you posted come from array_merge(); the output of array_merge(); should be exaclty what you need: print_r(array_merge($a,$b)); // outputs => Array ( [0] => a [1] => b [2] => c [3] => d )
I totally disagree with the term «append». Append really means that items of one array become elements of another (destination) array which might already has some elements, therefore changing the destination array. Merge allocates a new array and COPIES elements of both arrays, while append actually means reusing the destination array elements without extra memory allocation.
All methods are described on the page [PHP-docs] in «User Contributed Notes» [1]: php.net/manual/ru/function.array-push.php
11 Answers 11
$a = array('a', 'b'); $b = array('c', 'd'); $merge = array_merge($a, $b); // $merge is now equals to array('a','b','c','d');
$merge = $a + $b; // $merge now equals array('a','b')
Will not work, because the + operator does not actually merge them. If they $a has the same keys as $b , it won’t do anything.
Just be careful if your keys are not a numbers but strings, From doc: If the input arrays have the same string keys, then the later value for that key will overwrite the previous one
Another way to do this in PHP 5.6+ would be to use the . token
$a = array('a', 'b'); $b = array('c', 'd'); array_push($a, . $b); // $a is now equals to array('a','b','c','d');
This will also work with any Traversable
$a = array('a', 'b'); $b = new ArrayIterator(array('c', 'd')); array_push($a, . $b); // $a is now equals to array('a','b','c','d');
A warning though:
- in PHP versions before 7.3 this will cause a fatal error if $b is an empty array or not traversable e.g. not an array
- in PHP 7.3 a warning will be raised if $b is not traversable
Which term is used for such syntax? (E.g. in JS it is called spread operator ) Or can you provide link to docs?
The most useful answer when looking for a simple way to append an array to itself without overriding any previous elements.
A little note: This doesn’t work with associative arrays. (Fatal Error: Cannot unpack array with string keys)
Why don’t you want to use this, the correct, built-in method.
@KittenCodings — Read the «edit history» of the question. the original question was entitled PHP append one array to another (not array_merge or array_push) . subsequently modified to PHP append one array to another (not array_merge or +) before changing to its current title
@MarkBaker Wow! I didn’t know SO has an edit history! Sorry about that, and thanks, this changes a lot and somewhat prevents moderators from putting words into peoples mouths, I previously felt like some questions were defaced and their comments invalidated by content removed/edited, though I imagine most people probably don’t read the edit history, I sure as heck will from now on
It’s a pretty old post, but I want to add something about appending one array to another:
you can use array functions like this:
array_merge(array_values($array), array_values($appendArray));
array_merge doesn’t merge numeric keys so it appends all values of $appendArray. While using native php functions instead of a foreach-loop, it should be faster on arrays with a lot of elements.
Addition 2019-12-13: Since PHP 7.4, there is the possibility to append or prepend arrays the Array Spread Operator way:
As before, keys can be an issue with this new feature:
$a = ['a' => 3, 'b' => 4]; $b = ['c' => 1, 'a' => 2, . $a];
«Fatal error: Uncaught Error: Cannot unpack array with string keys»
$a = [3 => 3, 4 => 4]; $b = [1 => 1, 4 => 2, . $a];
array(4) < [1]=>int(1) [4]=> int(2) [5]=> int(3) [6]=> int(4) >
$a = [1 => 1, 2 => 2]; $b = [. $a, 3 => 3, 1 => 4];
array(3) < [0]=>int(1) [1]=> int(4) [3]=> int(3) >
Yes it is more safe just in case to extract the array_values so that you don’t merge into the same keys.
"JAVA", "b" => "ASP"); $array2 = array("c" => "C", "b" => "PHP"); echo "
Example 1 Output:
"; print_r(array_merge($array1,$array2)); // Example 2 [When you want to merge arrays having integer keys and //want to reset integer keys to start from 0 then use array_merge() function] $array3 =array(5 => "CSS",6 => "CSS3"); $array4 =array(8 => "JAVASCRIPT",9 => "HTML"); echo "
Example 2 Output:
"; print_r(array_merge($array3,$array4)); // Example 3 [When you want to merge arrays having integer keys and // want to retain integer keys as it is then use PLUS (+) operator to merge arrays] $array5 =array(5 => "CSS",6 => "CSS3"); $array6 =array(8 => "JAVASCRIPT",9 => "HTML"); echo "
Example 3 Output:
"; print_r($array5+$array6); // Example 4 [When single array pass to array_merge having integer keys // then the array return by array_merge have integer keys starting from 0] $array7 =array(3 => "CSS",4 => "CSS3"); echo "
Example 4 Output:
"; print_r(array_merge($array7)); ?>
Example 1 Output: Array ( [a] => JAVA [b] => PHP [c] => C ) Example 2 Output: Array ( [0] => CSS [1] => CSS3 [2] => JAVASCRIPT [3] => HTML ) Example 3 Output: Array ( [5] => CSS [6] => CSS3 [8] => JAVASCRIPT [9] => HTML ) Example 4 Output: Array ( [0] => CSS [1] => CSS3 )
you are quite thorough with your answer; of import for me is the example noting that when keys are the same (for associative arrays), array_merge might behave contrary to expectation for those who simply takes it at its name.
Following on from answer’s by bstoney and Snark I did some tests on the various methods:
// Test 1 (array_merge) $array1 = $array2 = array_fill(0, 50000, 'aa'); $start = microtime(true); $array1 = array_merge($array1, $array2); printf("Test 1: %.06f\n", microtime(true) - $start); // Test2 (foreach) $array1 = $array2 = array_fill(0, 50000, 'aa'); $start = microtime(true); foreach ($array2 as $v) < $array1[] = $v; >printf("Test 2: %.06f\n", microtime(true) - $start); // Test 3 (. token) // PHP 5.6+ and produces error if $array2 is empty $array1 = $array2 = array_fill(0, 50000, 'aa'); $start = microtime(true); array_push($array1, . $array2); printf("Test 3: %.06f\n", microtime(true) - $start);
Test 1: 0.002717 Test 2: 0.006922 Test 3: 0.004744
ORIGINAL: I believe as of PHP 7, method 3 is a significantly better alternative due to the way foreach loops now act, which is to make a copy of the array being iterated over.
Whilst method 3 isn’t strictly an answer to the criteria of ‘not array_push’ in the question, it is one line and the most high performance in all respects, I think the question was asked before the . syntax was an option.
UPDATE 25/03/2020: I’ve updated the test which was flawed as the variables weren’t reset. Interestingly (or confusingly) the results now show as test 1 being the fastest, where it was the slowest, having gone from 0.008392 to 0.002717! This can only be down to PHP updates, as this wouldn’t have been affected by the testing flaw.
So, the saga continues, I will start using array_merge from now on!
What is the best way in PHP to append one multidimensional array to another?
I need to glue a couple of indexed arrays containing n associative arrays each (example below). I don’t care about the indexes of the outer array, I care only for the keys from inner arrays. I’ve tried a couple of methods and (surprisingly) only one of them — the most ugly — actually works. So I began to wonder if there’s something clever/fast that I’m missing. PHP version: 5.3+ (if that matters) This is what I have:
$arrayA = array( array( 'foo' => 1, 'bar' => 2, 'baz' => 3 ), array( 'foo' => 12, 'bar' => 22, 'baz' => 32 ), ); $arrayB = array( array( 'foo' => 21, 'bar' => 22, 'baz' => 23 ), array( 'foo' => 212, 'bar' => 222, 'baz' => 232 ), );
$arrayC = array( array( 'foo' => 1, 'bar' => 2, 'baz' => 3 ), array( 'foo' => 12, 'bar' => 22, 'baz' => 32 ), array( 'foo' => 21, 'bar' => 22, 'baz' => 23 ), array( 'foo' => 212, 'bar' => 222, 'baz' => 232 ), );
$arrayD = $arrayA; foreach($arrayB as $value) < $arrayD[] = $value; >$arrayE = array_push($arrayA, $arrayB); $arrayF = $arrayA + $arrayB; $arrayG = array_merge($arrayA, $arrayB); print_r($arrayC == $arrayD); //TRUE - it works print_r($arrayC == $arrayE); //FALSE print_r($arrayC == $arrayF); //FALSE print_r($arrayC == $arrayG); //FALSE
$arrayD = $arrayA; foreach($arrayB as $value) < $arrayD[] = $value; >$arrayE = array_push($arrayA, $arrayB); //
Php add one array to another
- Program to Insert new item in array on any position in PHP
- PHP append one array to another
- How to delete an Element From an Array in PHP ?
- How to print all the values of an array in PHP ?
- How to perform Array Delete by Value Not Key in PHP ?
- Removing Array Element and Re-Indexing in PHP
- How to count all array elements in PHP ?
- How to insert an item at the beginning of an array in PHP ?
- PHP Check if two arrays contain same elements
- Merge two arrays keeping original keys in PHP
- PHP program to find the maximum and the minimum in array
- How to check a key exists in an array in PHP ?
- PHP | Second most frequent element in an array
- Sort array of objects by object fields in PHP
- PHP | Sort array of strings in natural and standard orders
PHP Function Based
- How to pass PHP Variables by reference ?
- How to format Phone Numbers in PHP ?
- How to use php serialize() and unserialize() Function
- Implementing callback in PHP
- PHP | Merging two or more arrays using array_merge()
- PHP program to print an arithmetic progression series using inbuilt functions
- How to prevent SQL Injection in PHP ?
- How to extract the user name from the email ID using PHP ?
- How to count rows in MySQL table in PHP ?
- How to parse a CSV File in PHP ?
- How to generate simple random password from a given string using PHP ?
- How to upload images in MySQL using PHP PDO ?
- How to check foreach Loop Key Value in PHP ?
- How to properly Format a Number With Leading Zeros in PHP ?
- How to get a File Extension in PHP ?
PHP Date Based
- How to get the current Date and Time in PHP ?
- PHP program to change date format
- How to convert DateTime to String using PHP ?
- How to get Time Difference in Minutes in PHP ?
- Return all dates between two dates in an array in PHP
- Sort an array of dates in PHP
- How to get the time of the last modification of the current page in PHP?
- How to convert a Date into Timestamp using PHP ?
- How to add 24 hours to a unix timestamp in php?
- Sort a multidimensional array by date element in PHP
- Convert timestamp to readable date/time in PHP
- PHP | Number of week days between two dates
- PHP | Converting string to Date and DateTime
- How to get last day of a month from date in PHP ?
PHP String Based
- PHP | Change strings in an array to uppercase
- How to convert first character of all the words uppercase using PHP ?
- How to get the last character of a string in PHP ?
- How to convert uppercase string to lowercase using PHP ?
- How to extract Numbers From a String in PHP ?
- How to replace String in PHP ?
- How to Encrypt and Decrypt a PHP String ?
- How to display string values within a table using PHP ?
- How to write Multi-Line Strings in PHP ?
- How to check if a String Contains a Substring in PHP ?
- How to append a string in PHP ?
- How to remove white spaces only beginning/end of a string using PHP ?
- How to Remove Special Character from String in PHP ?
- How to create a string by joining the array elements using PHP ?
- How to prepend a string in PHP ?