note 118498 deleted from language.references by cmb

From: Date: Wed, 16 Dec 2015 17:34:56 +0000
Subject: note 118498 deleted from language.references by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-204462@lists.php.net to get a copy of this message
Note Submitter: Someone ---- Another example of something to watch out for when using references with arrays. It seems that even an usused reference to an array cell modifies the *source* of the reference. Strange behavior for an assignment statement (is this why I've seen it written as an =& operator? - although this doesn't happen with regular variables). <?php $array1 = array(1,2); $x = &$array1[1]; // Unused reference $array2 = $array1; // reference now also applies to $array2 ! $array2[1]=22; // (changing [0] will not affect $array1) print_r($array1); ?> Produces: Array ( [0] => 1 [1] => 22 // var_dump() will show the & here ) //above was Noted By Dave at SymmetricDesign dot com// //and below is my opinion to this simple problem. // This is an normal referencing problem. when you gain an reference to a memory at some variable. this variable, means "memory itself". (in above example, this would be -> $x = &$array1[1]; // Unused reference) and you've copied original one($array1) to another one($array2). and the copy means "paste everything on itself". including references or pointers, etcs. so, when you copied $array1 to $array2, this $array2 has same referencers that original $array1 has. meaning that $x = &$array1[1] = &$array2[1]; and again i said above. this reference means "memory itself". when you choose to inserting some values to $array2[1], $x; reference is affected by $array2[1]'s value. because, in allocated memory, $array2[1] is a copy of $array1[1]. this means that $array2[1] = $array1[1], also means &$array2[1] = &$array1[1] as said above. this causes memory's value reallocation on $array1[1]. at this moment. the problem of this topic is cleared by '$x', the memory itself. and this problem was solved by unsetting the '$x'. this is what that bug(clearly, it's not a bug. it's just a missunderstanding) has triggered by. this topic was posted 7 years ago, but i just want to clarify that it's not a bug. if there's some problems in my notes, plz, note that on above.

« previous php.notes (#204462) next »