note 46590 added to language.references
| From: | jw at jwscripts dot com | Date: | Sat, 16 Oct 2004 12:18:04 +0000 |
| Subject: | note 46590 added to language.references | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-78657@lists.php.net to get a copy of this message | ||
Re-using variables which where references before, without unsetting them first, leads to unexpected
behaviour.
The following code:
<?php
$numbers = array();
for ($i = 1; $i < 4; $i++) {
$numbers[] = null;
$num = count($numbers);
$index =& $numbers[$num ? $num - 1 : $num];
$index = $i;
}
foreach ($numbers as $index) {
print "$index\n";
}
?>
Does not produce:
1
2
3
But instead:
1
2
2
Applying unset($index) before re-using the variable fixes this and the expected list will be
produced:
1
2
3
----
Manual Page -- http://www.php.net/manual/en/language.references.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+46590
Delete -- http://master.php.net/manage/user-notes.php?action=delete+46590&report=yes
Reason: bad code -- http://master.php.net/manage/user-notes.php?action=delete+46590&report=yes&reason=bad+code
Reason: spam -- http://master.php.net/manage/user-notes.php?action=delete+46590&report=yes&reason=spam
Reason: useless example -- http://master.php.net/manage/user-notes.php?action=delete+46590&report=yes&reason=useless+example
Reason: contains commercial links -- http://master.php.net/manage/user-notes.php?action=delete+46590&report=yes&reason=contains+commercial+links
Reason: useless note -- http://master.php.net/manage/user-notes.php?action=delete+46590&report=yes&reason=useless+note
Reject -- http://master.php.net/manage/user-notes.php?action=reject+46590&report=yes
Search -- http://master.php.net/manage/user-notes.php