LonghornPHP 2026

Voting

: zero plus six?
(Example: nine)

The Note You're Voting On

Someone
10 years ago
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'. unsetting this reference triggers memory reallocation of $array2[1]. this closes the reference link between the copied one($array1, which is the original) and copy($array2). this is where that bug(clearly, it's not a bug. it's just a missunderstanding) has triggered by. closing reference link makes two array object to be separated on memory. and this work was done through the unset() function. 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.

<< Back to user notes page

To Top