php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #15273 Reference to array breaks
Submitted: 2002-01-29 05:21 UTC Modified: 2002-07-03 22:12 UTC
From: mvl at nikhef dot nl Assigned:
Status: Not a bug Package: Arrays related
PHP Version: 4.1.1 OS: Linux
Private report: No CVE-ID: None
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: mvl at nikhef dot nl
New email:
PHP Version: OS:

 

 [2002-01-29 05:21 UTC] mvl at nikhef dot nl
Hi,

Below you will find a piece of code which is intended to make two two-dimensional arrays: $aa and $bb. In fact, both arrays should be the same, as far as I can see. It seems however that the unset($b_nw) is crucial. 

As far as I understood from the documentation, an assignement with an arrray on the right-hand side should perfrom a copy of the array. My assumption is that the same should be true with a reference to an array, because there is no way to distinguish between them. So please have a look at my code and tell me when you need more information, or if I misunderstood something.


The code:

<?php
   $a=array(0);
   $b=array(0);
   $aa=array(&$a);
   $bb=array(&$b);
   for ($i=1; $i<3; $i++) {
     $a_nw=$a;
     $a_nw[]=$i;
     $aa[]=&$a_nw;
     $b_nw=$b;
     $b_nw[]=$i;
     $bb[]=&$b_nw;
     unset($b_nw);
   }
   echo "<b>aa: </b>";
   print_r($aa);
   echo "<br>\n";
   echo "<b>bb: </b>";
   print_r($bb);
   echo "<br>\n";
?>


The output:
aa: Array ( [0] => Array ( [0] => 0 ) [1] => Array ( [0] => 0 [1] => 2 ) [2] => Array ( [0] => 0 [1] => 2 ) ) 
bb: Array ( [0] => Array ( [0] => 0 ) [1] => Array ( [0] => 0 [1] => 1 ) [2] => Array ( [0] => 0 [1] => 2 ) ) 

Note that $aa[1] != $bb[1], which is unexepected ($bb[1] is the correct value, I think).

Thanks,

Marco.

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2002-07-03 22:12 UTC] eru@php.net
It took me a while to realize it myself, but RTFMing helps:
http://www.php.net/manual/en/language.references.unset.php explains it quite well.
Through unset'ting the $b_nw; you turn the reference in $bb into a copy, that's why the array is not changing its values. On the other side, the [1]-entry in $aa remains a true reference, so when you change $a_nw in the second pass, you change the [1]-entry as well, as it is still a reference to $a_nw. If you use var_dump in exchange for print_r, you can see the references in the arrays much better, as they're prefixed with an ampersand.

Expected behaviour -> bogus.

 
PHP Copyright © 2001-2019 The PHP Group
All rights reserved.
Last updated: Mon Dec 09 16:01:24 2019 UTC