Re: foreach and current()
| From: | Nikita Popov | Date: | Mon, 18 Nov 2013 16:02:18 +0000 |
| Subject: | Re: foreach and current() | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-70194@lists.php.net to get a copy of this message | ||
On Mon, Nov 18, 2013 at 3:14 PM, Nicolai Scheer <scope@planetavent.de>wrote:
> Hi all!
>
> Has it been always the way, that it is not possible to use current() in a
> foreach loop?
>
> Just stumbled upon (using php 5.5.5):
>
> $arr = array( "a", "b", "c" );
>
> foreach( $arr as $entry )
> {
> #var_dump( current($arr) );
> }
>
> var_dump( current($arr) );
>
> Which yields "false", because the internal array pointer points behind the
> last element of $arr.
> If I uncomment the inner var_dump(), the script outputs "b" four times.
> This seems odd... I know that the documentation advises not to fiddle with
> the internal array pointer in a foreach loop, but current() should not
> affect it in any way and therefor should be safe to use.
>
> Does anyone know what the reasoning behind this behavious is?
>
The relation between foreach and current() is somewhat complex and depends
on the environment, in particular the refcount of the array, whether it is
a reference and whether the iteration happens by-reference. The exact
behavior and the reasons for it are outlined in
http://stackoverflow.com/questions/10057671/how-foreach-actually-works/14854568#14854568
.
I have a patch attached to bug #53405 (https://bugs.php.net/bug.php?id=53405)
to make foreach and current() fully independent (and provide generally
stronger independence and safety guarantees in that area), but it's a
somewhat tricky affair and I likely won't have time to finish this for 5.6.
Nikita