SunshinePHP 2019 CFP Started

Voting

Please answer this simple SPAM challenge: min(one, five)?
(Example: nine)

The Note You're Voting On

Dave at SymmetricDesigns dot com
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
    )

I fixed my bug by rewriting the code without references, but it can also be fixed with the unset() function:
<?php
    $array1
= array(1,2);
   
$x = &$array1[1];
   
$array2 = $array1;
    unset(
$x); // Array copy is now unaffected by above reference
   
$array2[1]=22;
   
print_r($array1);
?>
Produces:
    Array
    (
    [0] => 1
    [1] => 2
    )

<< Back to user notes page

To Top