Array offset error in PHP

$arr = array(1); $a = & $arr[0]; $arr2 = $arr; $arr2[0]++; echo $arr[0],$arr2[0]; // Output 2,2 

Could you help me how is this possible?

+5
php
source share
3 answers

Note, however, that references inside arrays are potentially dangerous. Performing a normal (not by reference) assignment using a link on the right side does not turn the left side into a link, but links inside arrays are stored in these normal tasks. This also applies to function calls in which 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 not a reference! */ 
+7
source share
 $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 ie 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 
0
source share

It looks like $ arr [0] and $ arr2 [0] point to the same allocated memory, so if you increase one of the pointers, int will increase in memory

Link Are there pointers in php?

-one
source share

All Articles