5
$arr = array(1);
$a = & $arr[0];

$arr2 = $arr;
$arr2[0]++;

echo $arr[0],$arr2[0];

// Output 2,2

Can you please help me how is it possible?

xdazz
  • 149,740
  • 33
  • 229
  • 258
som
  • 4,614
  • 2
  • 18
  • 36

3 Answers3

7

Note, however, that references inside arrays are potentially dangerous. Doing a normal (not by reference) assignment with a reference on the right side does not turn the left side into a reference, but references inside arrays are preserved in these normal assignments. This also applies to function calls where the array is passed by value.

/* Assignment of array variables */
$arr = array(1);
$a =& $arr[0]; //$a and $arr[0] are in the same reference set
$arr2 = $arr; //not an assignment-by-reference!
$arr2[0]++;
/* $a == 2, $arr == array(2) */
/* The contents of $arr are changed even though it's not a reference! */
xdazz
  • 149,740
  • 33
  • 229
  • 258
0
$arr = array(1);//creates an Array ( [0] => 1 ) and assigns it to $arr
$a = & $arr[0];//assigns by reference $arr[0] to $a and thus $a is a reference of $arr[0]. 
//Here $arr[0] is also replaced with the reference to the actual value i.e. 1

$arr2 = $arr;//assigns $arr to $arr2

$arr2[0]++;//increments the referenced value by one

echo $arr[0],$arr2[0];//As both $aar[0] and $arr2[0] are referencing the same block of memory so both echo 2

// Output 22
000
  • 3,818
  • 4
  • 21
  • 38
-1

It looks like $arr[0] and $arr2[0] are pointing to the same allocated memory, so if you increment on one of the pointers , the int will be increment in the memory

Link Are there pointers in php?

Community
  • 1
  • 1
Dukeatcoding
  • 1,326
  • 2
  • 19
  • 30