1

The question was what's gonna be printed when the code below is executed?

My answer was:

arr[0]=1 and arr2[0]=2

But apparently, no. As seen during execution, the answer appears to be arr[0]=2 and arr2[0]=2. Now, that confuses me - why would arr[0] be 2, if it wasn't even referenced, and as such shouldn't be changed when arr2[0] was modified?

$a = 1;
$arr = array(1);
$a = &$arr[0]; //$a=1
$arr2 = $arr;
$arr2[0]++; //$arr2[0]=2
echo "arr[0]=".$arr[0]. "<br>";
echo "arr2[0]=".$arr2[0]. "<br>";

I'm probably missing something embarrassingly obvious, but can't seem to figure it out. Thanks, in advance!

Agon Hoxha
  • 29
  • 3
  • 2
    `what's gonna be printed when the code below is executed?` - Hm? What about executing that code? – Marcin Orlowski Jun 05 '18 at 10:50
  • 1
    Question is misleading. You are asking what's gonna be printed when you have executed the code yourself and stating the results are different than what you expect. – Simos Fasouliotis Jun 05 '18 at 10:50
  • Take a look at [this](https://stackoverflow.com/a/2030924/4524061) answer –  Jun 05 '18 at 10:56
  • 1
    Fun fact: even though we never actually do something with `$a`, it still messes up what OP expected: https://3v4l.org/hqasB – Loek Jun 05 '18 at 11:01
  • Marcin, please read the question again. I did execute it. – Agon Hoxha Jun 05 '18 at 11:15
  • I'm not asking what's gonna be printed. I'm asking why that is printed, instead of the first one being 1 and the second one being 2. – Agon Hoxha Jun 05 '18 at 11:16

2 Answers2

0

By this assignment $a = &$arr[0]; you've created reference in $arr. This reference will then be copied to $arr2. If you call var_dump($arr, $arr2); you'll see that first element is a reference in both arrays.

This case is perfectly described in this comment at php.net.

Djengobarm
  • 398
  • 3
  • 7
0
<?php
$a = 1;
$arr = array(1);
$a = $arr[0]; //$a=1
$arr2 = $arr;
$arr2[0]++; //$arr2[0]=2
echo "arr[0]=".$arr[0]. "<br>";
echo "arr2[0]=".$arr2[0]. "<br>";

remove the & from $a = &$arr[0]; and you will get your expected result

Read more about ampersand in php Here!!!

pr1nc3
  • 8,108
  • 3
  • 23
  • 36