|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
[2016-01-28 12:43 UTC] bwoebi@php.net
[2016-05-31 08:01 UTC] cronfy at gmail dot com
[2016-05-31 16:55 UTC] cmb@php.net
[2016-05-31 17:00 UTC] cmb@php.net
-Status: Open
+Status: Closed
-Assigned To:
+Assigned To: cmb
[2016-05-31 17:00 UTC] cmb@php.net
[2020-02-07 06:07 UTC] phpdocbot@php.net
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Sat Nov 08 20:00:02 2025 UTC |
Description: ------------ Every other month there's a bug report about how having two foreach loops, the first with a reference and the second without, results in unexpected behavior. (The bug system suggested four of them to me now as possible duplicates of this.) While there is a warning in the documentation, "Warning Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset()." an example would be helpful to illustrate what the effects of that can look like to a developer. Plus it would make the warning box larger and more visible. An example such as: Test script: --------------- <?php $array = [1, 2, 3, 4, 5]; foreach ($array as &$n) { // $n is a reference to an item in $array $n = $n * 2; } // $array == [2, 4, 6, 8, 10] // without an unset($n), $n is still a reference to the last item: $array[4] foreach ($array as $k => $n) { // $array[4] will be updated with each value from $array... echo "{$k} => {$n} "; print_r($array); } // ...until ultimately the second-to-last value is copied onto the last value // output: // 0 => 2 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 8, [4] => 2 ) // 1 => 4 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 8, [4] => 4 ) // 2 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 8, [4] => 6 ) // 3 => 8 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 8, [4] => 8 ) // 4 => 8 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 8, [4] => 8 ) ?>