note 125151 added to control-structures.foreach
| From: | me@php.net | Date: | Sun, 28 Jun 2020 07:00:19 +0000 |
| Subject: | note 125151 added to control-structures.foreach | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-214814@lists.php.net to get a copy of this message | ||
It is not documented, but when modifying the array within foreach:
PHP seems to create a snapshot, or a copy of the entire array ("copy on write"?) when it
starts the foreach loop, so changes on the iterated array in the loop have no effect on the started
loop.
$a = [1,2,3];
foreach ($a as $key => $value) {
if($value == 1) {
$a[3] = 1;
$a[1] = 999999;
unset($a[0]);
echo "Inner loop start: \n";
foreach ($a as $key2 => $value2) {
echo "$key2 => $value2";
echo "\n";
}
echo "Inner loop end \n";
}
echo "$key => $value";
echo "\n";
}
echo "Next iteration: \n";
foreach ($a as $key => $value) {
echo "$key => $value";
echo "\n";
}
Result:
Inner loop start:
1 => 999999
2 => 3
3 => 1
Inner loop end
0 => 1
1 => 2
2 => 3
Next iteration:
1 => 999999
2 => 3
3 => 1
----
Server IP: 45.112.84.4
Probable Submitter: 103.51.166.36 (proxied: 178.223.177.145)
----
Manual Page -- http://php.net/manual/en/control-structures.foreach.php
Edit -- https://master.php.net/note/edit/125151
Del: integrated -- https://master.php.net/note/delete/125151/integrated
Del: useless -- https://master.php.net/note/delete/125151/useless
Del: bad code -- https://master.php.net/note/delete/125151/bad+code
Del: spam -- https://master.php.net/note/delete/125151/spam
Del: non-english -- https://master.php.net/note/delete/125151/non-english
Del: in docs -- https://master.php.net/note/delete/125151/in+docs
Del: other reasons-- https://master.php.net/note/delete/125151
Reject -- https://master.php.net/note/reject/125151
Search -- https://master.php.net/manage/user-notes.php