Concatenating arrays in PHP

Just a quick post so I know where to look the next time I forget how to concatenate arrays in PHP.

Use array_merge to concatenate two numerically-indexed arrays; not array_push and not the array union operator: +.


$first = array('doh', 'ray', 'me');
$second = array('fah', 'soh', 'lah', 'te', 'do');

echo "Union: ", var_export($first + $second, true), "n";
echo "Merge: ", var_export(array_merge($first, $second), true), "n";

// array_push returns int, not an array:
array_push($first, $second);
echo "Push: ", var_export($first, true), "n";

The output:

Union: array (
  0 => 'doh',
  1 => 'ray',
  2 => 'me',
  3 => 'te',
  4 => 'do',
)
Merge: array (
  0 => 'doh',
  1 => 'ray',
  2 => 'me',
  3 => 'fah',
  4 => 'soh',
  5 => 'lah',
  6 => 'te',
  7 => 'do',
)
Push: array (
  0 => 'doh',
  1 => 'ray',
  2 => 'me',
  3 => 
  array (
    0 => 'fah',
    1 => 'soh',
    2 => 'lah',
    3 => 'te',
    4 => 'do',
  ),
)
Posted Thursday, November 20th, 2008 under PHP, Tip.

8 comments

  1. Very good example.
    Exactly what I was looking for !

    thank you

  2. what if you have associative arrays ? how are you going to preserve the keys ?

  3. Use the array union operator ‘+’ for associative arrays (being careful how you order your associative arrays – put the arrays with keys and values you want to preserve as far to the left as possible.)

  4. Thanks.. useful post!

  5. exactly what I am looking for too

  6. Just what I wanted to know, thanks!