|
Posted by Usenet on 05/22/07 10:08
In article <f2lv8e$pk$1@nyytiset.pp.htv.fi>, Rami Elomaa wrote:
> $a = range(0,10);
> foreach($a as $key => $val)
> if($val%2)
> unset($a[$key]);
>
> I've done something like this and have never had any problems. I don't
> see the threats in this kind of thing, can you explain me what you think
> that might be unsafe in this method?
Unless I'm mistaken the potential problem lies in the possibility that the array
is indexed in such a way that, if you delete elements from it whilst something
(in this case "foreach" is working through it, the index that foreach is using
might be compromised and so the next iteration might not return the element that
the programmer was expecting.
The easiest way to see this occurring is to use a numeric index into the array,
*then* delete something from the middle of it whilst in a loop.
Good question Jon! 8-)
Regards
Mark
[Back to original message]
|