note 66000 added to control-structures.foreach

From: Date: Thu, 11 May 2006 18:25:02 +0000
Subject: note 66000 added to control-structures.foreach
Groups: php.notes 
Request: Send a blank email to php-notes+get-111146@lists.php.net to get a copy of this message
With foreach and references, there is a super easy way to corrupt your data see this test script: <?php $array = array(1,2,3); foreach( $array as &$item ); foreach( $array as $item ); print_r( $array ); ?> You would imagine that it would have 1,2,3 but in reality, it outputs 1,2,2 The issue is that $item is a pointer to the last array value, and exists outside of the scope of the foreach, so the second foreach overwrites the value. If you would check what it gets set to in the second foreach loop, you would see that it gets set to 1 and then 2 and then 2 again. This has already been filed as a bug, see: http://bugs.php.net/bug.php?id=29992 but php developers seem to think that it's expected behaviour and *good* behaviour, so it's doubtful that it will change anytime soon. This is a really bad gotcha, so watch out. ---- Server IP: 64.71.164.2 Probable Submitter: 67.183.76.48 ---- X-Spam-Status: No, hits=3.1 required=5.0 tests=DATE_MISSING,FROM_NO_LOWER autolearn=no version=2.64 ---- Manual Page -- http://www.php.net/manual/en/control-structures.foreach.php Edit -- http://master.php.net/note/edit/66000 Del: integrated -- http://master.php.net/note/delete/66000/integrated Del: useless -- http://master.php.net/note/delete/66000/useless Del: bad code -- http://master.php.net/note/delete/66000/bad+code Del: spam -- http://master.php.net/note/delete/66000/spam Del: non-english -- http://master.php.net/note/delete/66000/non-english Del: in docs -- http://master.php.net/note/delete/66000/in+docs Del: other reasons-- http://master.php.net/note/delete/66000 Reject -- http://master.php.net/note/reject/66000 Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#111146) next »