note 48173 deleted from control-structures.foreach by danbrown

From: Date: Tue, 28 Apr 2009 13:11:23 +0000
Subject: note 48173 deleted from control-structures.foreach by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-153927@lists.php.net to get a copy of this message
Note Submitter: ---- 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.

« previous php.notes (#153927) next »