|
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!
Navigation:
[Reply to this message]
|