On Tue, Jul 5, 2011 at 2:40 PM, Dajka Tamas <viper@xxxxxxxxxxx> wrote: > I've bumped into an interesting thing with foreach. I really don't know, if > this is normal working, or why it is, so I got curious. > > The script: > > foreach ( $cats as &$c ) { > echo $c['id']; > if ( $c['id'] < 5 ) { > $c['id']++; > $cats[] = $c; > } > } > > Input 1: > > $cats = array( array( 'id' => 1 ) ); > > Output 1: > > 1 > > Input 2: > > $cats = array( array( 'id' => 1 ), array( 'id' => 2 ) ); > > Output 2: > > 122334455 > > Why is this? Is this normal behaviour? > Looking at the implementation of foreach in the source, the pointer to the next item in the array is calculated after evaluating the condition but before executing that loop. Thus, with a single array element it decides it's at the end of the array before the first loop. My C is a little rusty so I might have the details slightly wrong, but that's the crux of what's happening. Whether that's normal and expected or a bug is one of the internals team, but my guess is that it's a "feature" rather than a bug. -Stuart -- Stuart Dallas 3ft9 Ltd http://3ft9.com/