Append One Array To Another In PHP

Appending arrays in PHP can be done with the array_merge() function. The array will take any number of arrays as arguments and will return a single array. Here is an example using just two arrays.

$array1 = array('item1', 'item2');
$array2 = array('item3', 'item4');
$array3 = array_merge($array1, $array2);
print_r($array3);

Will print out.

Array
(
 [0] => item1
 [1] => item2
 [2] => item3
 [3] => item4
)

You can also create arrays using the array command inside the parameter list.

$array1 = array('item1', 'item2');
$array2 = array('item3', 'item4');
$array3 = array_merge($array1, $array2, array('item5', 'item6'));
print_r($array3);
Will print off
Array
(
 [0] => item1
 [1] => item2
 [2] => item3
 [3] => item4
 [4] => item5
 [5] => item6
)
When merging arrays the numbering is reset.
$array1 = array();
$array2 = array(1 => 'item1');
$array3 = array_merge($array1, $array2);
print_r($array3);
Will print off.
Array
(
 [0] => item1
)
Associative keys are kept when merging arrays with keys. If the key of two arrays are the same then the fist array value will be overwritten by the value in the second array. Here is an example of this in action.
$array1 = array('item1' => 'item1', 'item2' => 'item2');
$array2 = array('item1' => 'item5', 'item2' => 'item6');
$array3 = array_merge($array1, $array2);
print_r($array3);
Produces the following result.
Array
(
 [item1] => item5
 [item2] => item6
)

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
11 + 0 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.