Reply to Re: For gurus: bug in php? Recursive foreach dont work properly.

Your name:

Reply:


Posted by Toby A Inkster on 04/12/07 08:56

Tamagafk wrote:

> Hi! Looks like there is a bug in php. If I have function which uses
> foreach to run trough array recursively, the lop-level foreach
> interupted by lover-level foreach'es. If I use simply 'for' everything
> is ok.

It's not a bug -- it's a "feature". Internally, arrays in PHP have a
"pointer" (not in the C sense of the word) which points at the "current"
element of array. foreach() uses this pointer to iterate through the
array. This is alluded to in the manual:

"the internal pointer of the original array *is*
advanced with the processing of the array."

So both foreach() functions are playing with the same internal pointer,
and screw things up for each other.

As an aside, you can use this internal pointer yourself via the following
functions:

each() - Returns current key, value pair
key() - Returns current key
current() - Returns current value
reset() - Reset pointer to start, return value
next() - Move pointer forwards, return value
prev() - Move pointer backwards, return value
end() - Move pointer to end, return value

Anyway, one solution is to either use for(), as you've discovered. This
works because instead of using PHP's internal array pointer to keep track
of your position in the array, you've defined your own pointer.

The other solution is to make a local copy of the array and run your
foreach() loop on that. Using for() is probably neater though.

--
Toby A Inkster BSc (Hons) ARCS
Contact Me ~ http://tobyinkster.co.uk/contact
Geek of ~ HTML/SQL/Perl/PHP/Python*/Apache/Linux

* = I'm getting there!

[Back to original message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация