note 113098 added to control-structures.foreach
| From: | Anonymous | Date: | Thu, 29 Aug 2013 08:21:26 +0000 |
| Subject: | note 113098 added to control-structures.foreach | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-196113@lists.php.net to get a copy of this message | ||
[quote]
I want to add some inline comments to dtowell's piece of code about the iteration by reference:
<?php
$a = array('abe','ben','cam');
foreach ($a as $k=>&$n)
$n = strtoupper($n);
# At the end of this cycle the variable $n refers to the same memory as $a[2]
# So when the second "foreach" assigns a value to $n :
foreach ($a as $k=>$n) // notice NO reference here!
echo "$n\n";
# it is also modifying $a[2] .
# So on the three repetitions of the second "foreach" the array will look like:
# 1. ('abe','ben','abe') - assigned the value of the first element to
the last element
# 2. ('abe','ben','ben') - assigned the value of the second element to
the last element
# 3. ('abe','ben','ben') - assigned the value of the third element to
itself
print_r($a);
?>
[/quote]
To resolve this problem - should always use unset after foreach:
<?php
$array = array('abe','ben','cam');
foreach ( $array as $key=>&$val ) {}
unset($key); unset($val);
foreach ( $array as $key=>$val ) {}
unset($key); unset($val);
print_r($array);
----
Server IP: 62.149.26.211
Probable Submitter: 195.184.209.115
----
Manual Page -- http://php.net/manual/en/control-structures.foreach.php
Edit -- https://master.php.net/note/edit/113098
Del: integrated -- https://master.php.net/note/delete/113098/integrated
Del: useless -- https://master.php.net/note/delete/113098/useless
Del: bad code -- https://master.php.net/note/delete/113098/bad+code
Del: spam -- https://master.php.net/note/delete/113098/spam
Del: non-english -- https://master.php.net/note/delete/113098/non-english
Del: in docs -- https://master.php.net/note/delete/113098/in+docs
Del: other reasons-- https://master.php.net/note/delete/113098
Reject -- https://master.php.net/note/reject/113098
Search -- https://master.php.net/manage/user-notes.php