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

Your name:

Reply:


Posted by Jerry Stuckle on 05/20/07 02:41

Rami Elomaa wrote:
> Jon Slaughter kirjoitti:
>> Is it safe to remove elements from an array that foreach is working
>> on? (normally this is not the case but not sure in php) If so is there
>> an efficient way to handle it? (I could add the indexes to a temp
>> array and delete afterwards if necessary but since I'm actually
>> working in a nested situation this could get a little messy. I guess I
>> could set there values to null and remove them afterwards?
>
> $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?
>

It is never safe to assume you can delete (or in this case unset)
something while it is in use. Results are usually very unpredictable.
It may work now - but may fail when you upgrade PHP, when you
restructure your code a little, or even under heavier load. The latter
two are spectacularly difficult to find!

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstucklex@attglobal.net
==================

[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

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