Reply to Re: safe to delete elements of array in foreach

Your name:

Reply:


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]


Удаленная работа для программистов  •  Как заработать на 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

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