note 113098 deleted from control-structures.foreach by tularis
| From: | tularis@php.net | Date: | Fri, 14 Nov 2014 23:32:10 +0000 |
| Subject: | note 113098 deleted from control-structures.foreach by tularis | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-200911@lists.php.net to get a copy of this message | ||
Note Submitter: Anonymous
----
[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);