|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
[2005-02-15 01:30 UTC] tony2001@php.net
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Wed Nov 19 12:00:02 2025 UTC |
Description: ------------ Array's internal pointer (which one can manipulate by next, prev, current, etc. functions) has invalid bahavior in foreach statement. Moreover, there is a contradictional description of this behavior in the manual. from manual: "Note: Also note that foreach operates on a copy of the specified array and not the array itself. Therefore, the ARRAY POINTER IS NOT MODIFIED as with the each() construct, and changes to the array element returned are not reflected in the original array. However, the INTERNAL POINTER OF THE ORIGINAL ARRAY IS ADVANCED with the processing of the array. Assuming the foreach loop runs to completion, the array's internal pointer will be at the end of the array. " It is not clear whether or not the internal pointer of the original array is advanced during enumeration. I made some tests and it seems to me that foreach statement mishandles array's internal pointer (see "reproducable code"). I would prefer if the original array's pointer was not influenced by foreach statement because one can do changes in the array during enumeration (which is legal since it is assumed that foreach operates on a copy) and IMHO any changes to the pointer in original array would necessarily lead to strange behavior. Reproduce code: --------------- echo "-- a --\n"; $a = array(0,1,2); var_dump(current($a)); foreach ($a as $value) { /* do not touch $a */ } var_dump(current($a)); $b = array(0,1,2); echo "-- b --\n"; var_dump(current($b)); foreach ($b as $value) { var_dump(current($b)); } var_dump(current($b)); Expected result: ---------------- either the following (pointer is advanced): -- a -- int(0) bool(false) -- b -- int(0) int(0) int(1) int(2) int(false) or the following (pointer is not avanced): -- a -- int(0) int(0) -- b -- int(0) int(0) int(0) int(0) int(0) Actual result: -------------- -- a -- int(0) bool(false) -- b -- int(0) int(0) int(0) int(0) int(0)