You cannot assign something by reference unless you link to something that already exists. Similarly, you cannot copy what does not exist.
So this code:
$a = array(1,2,3);
... no copy, no link - 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 to array 1 . The variables used to initialize the array values ββstill exist on their own and can be changed 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 links to $x , $y and $z (note the & ). If after running this code I change $x - let's say I give it a value of 4 - it will also change the first value in the array. Therefore, when you use an array, $a[0] will now contain 4 .
See this section of the manual for more information on how reference works in PHP.
1 Depending on the types and values ββof the variables used as elements of the array, the copy operation may not occur during assignment even when assigned by value. PHP internally uses copy-on-write as much as possible for performance and memory efficiency reasons. However, in terms of behavior in the context of your code, you can think of it as a simple copy.
Daverandom
source share