note 18803 deleted from control-structures.foreach by sniper
| From: | sniper@php.net | Date: | Wed, 08 Oct 2003 04:10:05 +0000 |
| Subject: | note 18803 deleted from control-structures.foreach by sniper | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-58012@lists.php.net to get a copy of this message | ||
Note Submitter: DONTSPAM.thomas@pixtur.de
----
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 :-) ).