note 50072 deleted from control-structures.while by philip

From: Date: Thu, 27 Apr 2006 15:53:36 +0000
Subject: note 50072 deleted from control-structures.while by philip
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-109865@lists.php.net to get a copy of this message
Note Submitter: mortoray at ecircle-ag dot com ---- 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.

« previous php.notes (#109865) next »