Question

I've seen the following often lately and I'm wondering what it does? I can't seem to find it in the PHP manual.

 $arr1 = array('key' => 'value1');
 $arr2 = array('key' => 'value2');
 $arr1 += $arr2;

Is it similar to an array_merge?

I know what the following does, but I don't understand what it does when working with an array:

 $var1 = 1;
 $var2 = 2;
 $var1 += $var2;
 echo $var1; // 3
Was it helpful?

Solution

The + operation between two arrays acts like a UNION.

OTHER TIPS

$arr1 += $arr2 is short for $arr1 = $arr1 + $arr2.

The + array operator does the following:

  • Create a new array that contains all the elements of $arr1 and $arr2, except for the next condition.
  • If both operands have elements with the same key, only the element of $arr1 will be present.
  • The elements of $arr2 will be after those of $arr1.

This is different from array_merge, which:

  • Creates a new array that contains all the elements of $arr1 and $arr2, except for the next condition.
  • If both operands have elements with the same string key, only the element of $arr2 will be present.
  • Elements with numeric keys will be renumbered from 0, starting with the elements of $arr1, and then moving to the elements of $arr2.
  • The elements of $arr2 will be after those of $arr1, except the string elements, which will be in the position of the first array in which they appear.

Example:

<?php
$arr1 = array(1 => 'value1.1', 10 => 'value1.2', 's' => 'value1.s');
$arr2 = array(1 => 'value2', 2=> 'value2.2', 's' => 'value2.s');
var_dump(array_merge($arr1,$arr2));
$arr1 += $arr2;
var_dump($arr1);

Result (edited for clarity):

array(5) {
  [0]   => string(8) "value1.1"
  [1]   => string(8) "value1.2"
  ["s"] => string(8) "value2.s"
  [2]   => string(6) "value2"
  [3]   => string(8) "value2.2"
}
array(4) {
  [1]   => string(8) "value1.1"
  [10]  => string(8) "value1.2"
  ["s"] => string(8) "value1.s"
  [2]   => string(8) "value2.2"
}

The + operator in PHP when applied to arrays does the job of array UNION.

$arr += array $arr1;

effectively finds the union of $arr and $arr1 and assigns the result to $arr.

The difference between array_merge(), and the sum of two arrays is evident in the following examples:

$array1 = array();
$array2 = array(1 => "data");
$result = array_merge($array1, $array2);

$result would contain an array with index 0.

$array1 = array();
$array2 = array(1 => "data");
$result = $array1 + $array2;

The index is not changed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top