note 50072 added to control-structures.while

From: Date: Thu, 17 Feb 2005 09:15:26 +0000
Subject: note 50072 added to control-structures.while
Groups: php.notes 
Request: Send a blank email to php-notes+get-85152@lists.php.net to get a copy of this message
Note that while loops (and likely for, if's, and otherwise) do not introduce a new variable locality, that is, variables introduced in the loop will exist outside the loop and/or retain their value on further iterations of the loop. while( true ) { $val = 15; break; } print( "$val" ); //prints 15 This can introduce an insidious bug if you are using references. By Example: $i = 0; $set = array(); while( $i < 5 ) { $item = $i; $set[] =& $item; $i++; } print_r( $set ); Every item in the array has a value of 4, probably not what you were expecting/wanting. To do what you expect add a unset statement like this: $i = 0; $set = array(); while( $i < 5 ) { unset( $item ); $item = $i; $set[] =& $item; $i++; } print_r( $set ); Obviously for integers you wouldn't use refereneces, but if you are using classes or arrays this problem comes up. ---- Manual Page -- http://www.php.net/manual/en/control-structures.while.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+50072 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+50072&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+50072&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+50072&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+50072&report=yes&reason=useless Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+50072&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+50072&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#85152) next »