Append One Array To Another In PHP

12th February 2008

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.

  1. $array1 = array('item1', 'item2');
  2. $array2 = array('item3', 'item4');
  3. $array3 = array_merge($array1, $array2);
  4. print_r($array3);

Will print out.

  1. Array
  2. (
  3. [0] => item1
  4. [1] => item2
  5. [2] => item3
  6. [3] => item4
  7. )

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

  1. $array1 = array('item1', 'item2');
  2. $array2 = array('item3', 'item4');
  3. $array3 = array_merge($array1, $array2, array('item5', 'item6'));
  4. print_r($array3);
Will print off
  1. Array
  2. (
  3. [0] => item1
  4. [1] => item2
  5. [2] => item3
  6. [3] => item4
  7. [4] => item5
  8. [5] => item6
  9. )
When merging arrays the numbering is reset.
  1. $array1 = array();
  2. $array2 = array(1 => 'item1');
  3. $array3 = array_merge($array1, $array2);
  4. print_r($array3);
Will print off.
  1. Array
  2. (
  3. [0] => item1
  4. )
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.
  1. $array1 = array('item1' => 'item1', 'item2' => 'item2');
  2. $array2 = array('item1' => 'item5', 'item2' => 'item6');
  3. $array3 = array_merge($array1, $array2);
  4. print_r($array3);
Produces the following result.
  1. Array
  2. (
  3. [item1] => item5
  4. [item2] => item6
  5. )

Add new comment

The content of this field is kept private and will not be shown publicly.