note 48173 added to control-structures.foreach

From: Date: Tue, 14 Dec 2004 15:29:43 +0000
Subject: note 48173 added to control-structures.foreach
Groups: php.notes 
Request: Send a blank email to php-notes+get-81781@lists.php.net to get a copy of this message
This is a summary of bug report #26396 having status "wont fix", so the following is not a bug (report), but may need extra highlighting so the novice programmer (like me) can make sense of the second note given above. 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. <? $myArray = array("a", "b"); foreach($myArray as $anElement) { foreach($myArray as $anotherElement) { echo $anotherElement; } } ?> results in "abab", as each foreach works on a copy of $myArray. However: <? $myArray = array("a", "b"); function b() { global $myArray; foreach($myArray as $anotherElement) { echo $anotherElement; } } function a() { global $myArray; foreach($myArray as $anElement) { b(); } } a(); ?> results in "ab", ie. both foreach work on the same instance of $myArray because it is referenced as a global variable. Nevertheless, to the casual observer both variants seem equivalent and therefore should produce the same output. ---- Manual Page -- http://www.php.net/manual/en/control-structures.foreach.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+48173 Delete -- http://master.php.net/manage/user-notes.php?action=delete+48173&report=yes Reason: bad code -- http://master.php.net/manage/user-notes.php?action=delete+48173&report=yes&reason=bad+code Reason: spam -- http://master.php.net/manage/user-notes.php?action=delete+48173&report=yes&reason=spam Reason: useless example -- http://master.php.net/manage/user-notes.php?action=delete+48173&report=yes&reason=useless+example Reason: contains commercial links -- http://master.php.net/manage/user-notes.php?action=delete+48173&report=yes&reason=contains+commercial+links Reason: useless note -- http://master.php.net/manage/user-notes.php?action=delete+48173&report=yes&reason=useless+note Reject -- http://master.php.net/manage/user-notes.php?action=reject+48173&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#81781) next »