Re: foreach and current()
| From: | Alexey Zakhlestin | Date: | Mon, 18 Nov 2013 14:40:18 +0000 |
| Subject: | Re: foreach and current() | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-70192@lists.php.net to get a copy of this message | ||
On 18.11.13, 18:14, Nicolai Scheer 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?
current() implementation predates foreach and is totally separate. Main
difference is, that current()'s "pointer" is attached to the array, and
foreach's pointer is external.
so you can not run several each()/current() loops on array at the same
time, but you can have any number of nested foreach's iterating over the
same array independently.
They can't really be combined because of backwards compatibility
--
Alexey Zakhlestin
CTO at Grids.by/you
https://github.com/indeyets
PGP key: http://indeyets.ru/alexey.zakhlestin.pgp.asc
Attachment: [application/pgp-signature] OpenPGP digital signature signature.asc
Attachment: [application/pgp-signature] OpenPGP digital signature signature.asc