note 72301 added to language.references.whatdo

From: Date: Fri, 12 Jan 2007 09:17:41 +0000
Subject: note 72301 added to language.references.whatdo
Groups: php.notes 
Request: Send a blank email to php-notes+get-121574@lists.php.net to get a copy of this message
I want to add an example for the following sentence from this page of manual: "Note: If array with references is copied, its values are not dereferenced. This is valid also for arrays passed by value to functions." I ran into problems when using a code like this: <?php $a = 1; $b = array( 'id' => 1, 'children' => & $a, // reference to $a ); $c = $b; // copying and array - $a is copy of $b $c['children'] = 2; echo '<pre>$a = '; print_r($a); echo '</pre>'; echo '<pre>$b = '; print_r($b); echo '</pre>'; ?> This will output: $a = 2 $b = Array ( [id] => 1 [children] => 2 ) As is stated in cited note, when copying an array, it's elements are not dereferenced. This mean that element, that was reference in original array, in the copy of the array is still the reference to the original variable. In my example changing $c['children'] changes also $b['children'] and even the original variable: $a! In $c, the 'children' elements stays a reference to $a as in the orignal table. If you want to change 'children' only in $c, do the following: <?php unset($c['children']); $c['children'] = 2; ?> $a and $b['children'] will stay unchanged. I hope this will help somebody :-) ---- Server IP: 195.136.184.34 Probable Submitter: 212.14.58.157 ---- Manual Page -- http://www.php.net/manual/en/language.references.whatdo.php Edit -- https://master.php.net/note/edit/72301 Del: integrated -- https://master.php.net/note/delete/72301/integrated Del: useless -- https://master.php.net/note/delete/72301/useless Del: bad code -- https://master.php.net/note/delete/72301/bad+code Del: spam -- https://master.php.net/note/delete/72301/spam Del: non-english -- https://master.php.net/note/delete/72301/non-english Del: in docs -- https://master.php.net/note/delete/72301/in+docs Del: other reasons-- https://master.php.net/note/delete/72301 Reject -- https://master.php.net/note/reject/72301 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#121574) next »