php array assign by copying value or by reference? [duplicate]

微笑、不失礼 提交于 2019-11-29 06:19:38
Michael Berkowski

Assigning arrays by reference is possible when assigning array variables to other variables:

// By value...
$a = array(1,2,3);
$b = $a;
array_push($a, 5);
print_r($b);

// $b is not a reference to $a
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)

// By Reference
$a = array(1,2,3);
$b = &$a; // Here we assign by reference
array_push($a, 5);
print_r($b);

// $b is a reference to $a and gets the new value (3 => 5)
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 5
)

You can't assign something by reference unless you are referencing something that already exists. Equally, you can't copy something that doesn't exist.

So this code:

$a = array(1,2,3);

...neither copies or references - it just creates a new array fills it with values, because the values were specified literally.

However, this code:

$x = 1;
$y = 2;
$z = 3;
$a = array($x,$y,$z);

...copies the values from $x, $y and $z into an array1. The variables used to initialise the array values still exist in their own right, and can be modified or destroyed without affecting the values in the array.

This code:

$x = 1;
$y = 2;
$z = 3;
$a = array(&$x,&$y,&$z);

...creates an array of references to $x, $y and $z (notice the &). If, after running this code, I modify $x - let's say I give it a value of 4 - it will also modify the first value in the array. So when you use the array, $a[0] will now contain 4.

See this section of the manual for more information of how reference work in PHP.


1Depending on the types and values of the variables used as the array members, the copy operation may not happen at the time of the assignment even when assigned by-value. Internally PHP uses copy-on-write in as many situations as possible for reasons of performance and memory efficiency. However, in terms of the behaviour in the context of your code, you can treat it as a simple copy.

Evert

Yes, use &

$a = array(&$b, &$c, &$d);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!