|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
[2008-02-20 14:48 UTC] dmitry@php.net
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Thu Nov 06 16:00:01 2025 UTC |
Description: ------------ The problem is that when you reference an array element (say, n) and then use the same name (as the reference) as the current element value alias inside foreach, two things happen: 1. inside the foreach body the n element is replaced with the n-1 element; 2. and after the foreach run the n element is replaced with the last array element. Reproduce code: --------------- <?php $arr = array(); for ($i = 0; $i < 4; ++$i) { $arr[$i] = $i; } $el = &$arr[2]; print_r($arr); foreach ($arr as $el) { echo "el: $el\n"; } print_r($arr); ?> Expected result: ---------------- Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 ) el: 0 el: 1 el: 2 el: 3 Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 ) Actual result: -------------- Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 ) el: 0 el: 1 el: 1 el: 3 Array ( [0] => 0 [1] => 1 [2] => 3 [3] => 3 )