note 83325 added to language.references

From: Date: Wed, 21 May 2008 06:24:39 +0000
Subject: note 83325 added to language.references
Groups: php.notes 
Request: Send a blank email to php-notes+get-139570@lists.php.net to get a copy of this message
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 ) ---- Server IP: 69.147.83.197 Probable Submitter: 71.58.54.145 ---- Manual Page -- http://www.php.net/manual/en/language.references.php Edit -- https://master.php.net/note/edit/83325 Del: integrated -- https://master.php.net/note/delete/83325/integrated Del: useless -- https://master.php.net/note/delete/83325/useless Del: bad code -- https://master.php.net/note/delete/83325/bad+code Del: spam -- https://master.php.net/note/delete/83325/spam Del: non-english -- https://master.php.net/note/delete/83325/non-english Del: in docs -- https://master.php.net/note/delete/83325/in+docs Del: other reasons-- https://master.php.net/note/delete/83325 Reject -- https://master.php.net/note/reject/83325 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#139570) next »