note 53411 added to function.array

From: Date: Tue, 31 May 2005 21:52:11 +0000
Subject: note 53411 added to function.array
Groups: php.notes 
Request: Send a blank email to php-notes+get-89706@lists.php.net to get a copy of this message
How to use array() to create an array of references rather than of copies? (Especially needed when dealing with objects.) I played around somewhat and found a solution: place & before the parameters of array() that shall be references. My PHP version is 4.3.10. Demonstration: <?php $ref1 = 'unchanged'; $ref2 = & $ref1; $array_of_copies = array($ref1, $ref2); print_r($array_of_copies); // prints: Array ( [0] => unchanged [1] => unchanged ) $array_of_copies[0] = 'changed'; // $ref1 = 'changed'; is not equivalent, as it was _copied_ to the array print_r($array_of_copies); // prints: Array ( [0] => changed [1] => unchanged ) $array_of_refs = array(& $ref1, & $ref2); // the difference: place & before arguments print_r($array_of_refs); // prints: Array ( [0] => unchanged [1] => unchanged ) $array_of_refs[0] = 'changed'; // $ref1 = 'changed'; is equivalent as $array_of_refs[0] references $ref1 print_r($array_of_refs, true); // prints: Array ( [0] => changed [1] => changed ) ?> ---- Manual Page -- http://www.php.net/manual/en/function.array.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+53411 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+53411&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+53411&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+53411&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+53411&report=yes&reason=useless Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+53411&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+53411&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#89706) next »