Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP append one array to another (not array_push or +)

How to append one array to another without comparing their keys?

$a = array( 'a', 'b' ); $b = array( 'c', 'd' ); 

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 ) 

It just should be something, doing this, but in a more elegant way:

foreach ( $b AS $var )     $a[] = $var; 
like image 621
Danil K Avatar asked Nov 24 '10 16:11

Danil K


People also ask

How can I add one 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" );

How do I append one array to another array?

To append one array to another, call the concat() method on the first array, passing it the second array as a parameter, e.g. const arr3 = arr1. concat(arr2) . The concat method will merge the two arrays and will return a new array.

How do I copy one array to another in PHP?

The getArrayCopy() function of the ArrayObject class in PHP is used to create a copy of this ArrayObject. This function returns the copy of the array present in this ArrayObject.

Can you add to an array in PHP?

Definition and Usage. The array_push() function inserts one or more elements to the end of an array. Tip: You can add one value, or as many as you like. Note: Even if your array has string keys, your added elements will always have numeric keys (See example below).


1 Answers

array_merge is the elegant way:

$a = array('a', 'b'); $b = array('c', 'd'); $merge = array_merge($a, $b);  // $merge is now equals to array('a','b','c','d'); 

Doing something like:

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

like image 147
netcoder Avatar answered Sep 19 '22 10:09

netcoder