note 18803 added to control-structures.foreach

From: Date: Wed, 06 Feb 2002 11:45:54 +0000
Subject: note 18803 added to control-structures.foreach
Groups: php.notes 
Request: Send a blank email to php-notes+get-26287@lists.php.net to get a copy of this message
Just a small warning about referencing foreach-iterators. Iterating over an array which contains assosiative arrays can be tricky: Note this: $fields=array( array('name'=>'a name', 'text'=> 'some text'), array('name'=> 'name2', 'text'=>'more text') ); foreach( $fields as $key=>$value) { $nth_field=& $fields[$key]; # do some thing here unset($nth_field); #sometimes necessaray } Iterating over this array might overwrite the last element of the array by its precessor. Don´t know, if this a bug, but closing each iteration by adding the line "unset($nth_field);" will fix this behaviour. This error gave me a headache for some minutes, so I though, its nice to share it here. IMO, if the foreach-behaviour is not changed (improved) in near future, to allow iterating by reference, it will be a real argument for perl. The foreach-statement is quiet good for writing small, clean and read-able code (in perl :-) ). -- http://www.php.net/manual/en/control-structures.foreach.php http://master.php.net/manage/user-notes.php?action=edit+18803 http://master.php.net/manage/user-notes.php?action=delete+18803 http://master.php.net/manage/user-notes.php?action=reject+18803

« previous php.notes (#26287) next »