note 76292 added to function.array-shift
| From: | Traps at osu1 dot php dot net | Date: | Mon, 09 Jul 2007 17:52:22 +0000 |
| Subject: | note 76292 added to function.array-shift | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-128333@lists.php.net to get a copy of this message | ||
For those that may be trying to use array_shift() with an array containing references (e.g. working
with linked node trees), beware that array_shift() may not work as you expect: it will return a
*copy* of the first element of the array, and not the element itself, so your reference will be
lost.
The solution is to reference the first element before removing it with array_shift():
<?php
// using only array_shift:
$a = 1;
$array = array(&$a);
$b =& array_shift($array);
$b = 2;
echo "a = $a, b = $b<br>"; // outputs a = 1, b = 2
// solution: referencing the first element first:
$a = 1;
$array = array(&$a);
$b =& $array[0];
array_shift($array);
$b = 2;
echo "a = $a, b = $b<br>"; // outputs a = 2, b = 2
?>
----
Server IP: 81.92.200.26
Probable Submitter: 195.23.203.25
----
Manual Page -- http://www.php.net/manual/en/function.array-shift.php
Edit -- https://master.php.net/note/edit/76292
Del: integrated -- https://master.php.net/note/delete/76292/integrated
Del: useless -- https://master.php.net/note/delete/76292/useless
Del: bad code -- https://master.php.net/note/delete/76292/bad+code
Del: spam -- https://master.php.net/note/delete/76292/spam
Del: non-english -- https://master.php.net/note/delete/76292/non-english
Del: in docs -- https://master.php.net/note/delete/76292/in+docs
Del: other reasons-- https://master.php.net/note/delete/76292
Reject -- https://master.php.net/note/reject/76292
Search -- https://master.php.net/manage/user-notes.php