Assigning php array by copying value or reference?

Possible duplicate:
are arrays in php passed by value or by reference?

I heard that PHP can choose how to assign arrays, depending on the size of the array. It can be assigned by copying a value (like any scalar type) or by reference.

PHP always assigns an array to variables by copying the value, as the manual says.

Or can it be assigned by reference.?

<?php $a = array(1,2,3); ?> 
+7
source share
3 answers

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 ) 
+15
source

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.

+13
source

Yes, use &

 $a = array(&$b, &$c, &$d); 
+1
source

All Articles