Joining arrays in PHP

PHP has many methods to join arrays.

  • The plus + symbol will do a union of two arrays, preserving keys in the first array.
  • array_merge will do a union of two arrays, overwriting keys from the first array.
php > $a = array('one' => 'foo', 'two' => 'bar');
php > $b = array('two' => 'yin', 'three' => 'yang');
php > print_r($a + $b);
Array
(
    [one] => foo
    [two] => bar
    [three] => yang
)
php > print_r(array_merge($a, $b));
Array
(
    [one] => foo
    [two] => yin
    [three] => yang
)

We also have intersection with array_intersect, difference with array_diff and many more - see Array Functions.

Last modified: 03/03/2013 Tags:

This website is a personal resource. Nothing here is guaranteed correct or complete, so use at your own risk and try not to delete the Internet. -Stephan

Site Info

Privacy policy

Go to top