简体   繁体   中英

Array reference confusion in PHP

$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?

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! */
$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

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM