Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Regular Coder
    Join Date
    Oct 2008
    Posts
    214
    Thanks
    5
    Thanked 22 Times in 22 Posts

    PHP arrays and reference operator (&) bug (?)

    See the following simple code snippet...

    You have a source array, then you use some reference operator on that array (pretty useless in this snippet, but can happen in real world case like a "foreach ($source as &$currSource)") then you copy (duplicate) the array in another variable. Then you modify the content of the copy and the original is modified too!

    I don't understand why. Seems like a PHP bug to me or a misunderstanding of PHP references on my side.

    PHP Code:
    $source = array('apple''banana''strawberry');

    $dummy = &$source[1]; /* If you use a reference operator (&) on an array,
    any modification on a COPY of that array will also modify the ORIGINAL array! */

    $copySource $source;
    $copySource[1] = 'orange';

    print_r($source); /* Output Array ( [0] => apple [1] => orange [2] => strawberry )! Why? */ 
    Thank you!

    Alexandre.

  • #2
    Regular Coder
    Join Date
    Oct 2008
    Posts
    214
    Thanks
    5
    Thanked 22 Times in 22 Posts
    Found out the solution myself... This is indeed a very old bug in PHP still present in 5.3.0 (and will probably be there a wile).

    Due to peculiarities of the internal workings of PHP, if a reference is made to a single element of an array and then the array is copied, whether by assignment or when passed by value in a function call, the reference is copied as part of the array. This means that changes to any such elements in either array will be duplicated in the other array (and in the other references), even if the arrays have different scopes (e.g. one is an argument inside a function and the other is global)! Elements that did not have references at the time of the copy, as well as references assigned to those other elements after the copy of the array, will behave normally (i.e. independent of the other array).
    http://bugs.php.net/bug.php?id=20993
    http://bugs.php.net/bug.php?id=15025
    http://www.php.net/manual/en/languag...nces.php#79220

    This will not be fixed anytime soon. It is a deep seated problem in the implementation and fixing it would cause speed problems and numerous other problems, This is somthing that can be coded around too so should not cause massive problems.
    http://bugs.php.net/bug.php?id=8130


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •