Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does $array2 += $array1 do?

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
like image 957
Darryl Hein Avatar asked Aug 23 '10 03:08

Darryl Hein


4 Answers

$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"
}
like image 128
Artefacto Avatar answered Oct 21 '22 16:10

Artefacto


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.

like image 27
codaddict Avatar answered Oct 21 '22 14:10

codaddict


The + operation between two arrays acts like a UNION.

like image 38
Cᴏʀʏ Avatar answered Oct 21 '22 14:10

Cᴏʀʏ


One of the differences between array_merge(), and the sum of two arrays is evident in the following snippets. (See also https://3v4l.org/TcNBF.)

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

The index in $result will be 0.

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

The index is not changed; the index is still 1.

like image 24
apaderno Avatar answered Oct 21 '22 16:10

apaderno