Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Array reference confusion

With this code:

$a[1]=1;
$a[2]=& $a[1];

$b=$a;
$b[2]=7;

print_r($a);

I was expecting output to be 1 because $a is not assigned by reference to $b ($a = & $b) but it comes out to be 7. Why?


1 Answers

You're copying the array by value, but the elements of the source array are references. These references are just shallow-copied to the destination.

php > var_dump($a);
array(2) {
  [1]=>
  &int(1)
  [2]=>
  &int(1)
}
php > $b=$a;
php > var_dump($b);
array(2) {
  [1]=>
  &int(1)
  [2]=>
  &int(1)
}

Here's an example copying the array by reference:

php > $c[1] = 1;
php > $c[2] =& $c[1];
php > var_dump($c);
array(2) {         
  [1]=>            
  &int(1)
  [2]=>
  &int(1)
}
php > $d =& $c;
php > var_dump($d);
array(2) {
  [1]=>
  &int(1)
  [2]=>
  &int(1)
}
php > $d = array(3,4,5);
php > var_dump($c);
array(3) {
  [0]=>
  int(3)
  [1]=>
  int(4)
  [2]=>
  int(5)
}
php > var_dump($d);
array(3) {
  [0]=>
  int(3)
  [1]=>
  int(4)
  [2]=>
  int(5)
}

As you can see, the array variable (not elements) itself is a reference, so modifying $d affects $c. Reassigning $b itself has no effect on $a.

like image 165
Matthew Flaschen Avatar answered Feb 23 '26 14:02

Matthew Flaschen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!