note 61673 deleted from control-structures.foreach by googleguy
| From: | googleguy@php.net | Date: | Wed, 14 Nov 2012 22:33:29 +0000 |
| Subject: | note 61673 deleted from control-structures.foreach by googleguy | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-191978@lists.php.net to get a copy of this message | ||
Note Submitter: daniel dot oconnor at gmail dot com
----
Dangers with References
<?php
$months = array("Jan", "Feb", "March");
foreach ($months as &$month) {
$month .= "Beep";
}
print_r($months);
foreach ($months as $month) {
printf("%s\n", $month);
}
?>
Because $month is a reference to $months[2], iterating again with the same varible name causes
$months[2] to be overwritten! Oh no!
Ouput:
Array
(
[0] => JanBeep
[1] => FebBeep
[2] => MarchBeep
)
JanBeep
FebBeep
FebBeep