Re: modifying within foreach

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Tue, 2009-06-23 at 15:07 -0400, Eddie Drapkin wrote:
> It's just foreach($foo as $key => &$item) { }
> 
> You can't assign the key by reference >.>
> 
> On Tue, Jun 23, 2009 at 3:04 PM, Ashley
> Sheridan<ash@xxxxxxxxxxxxxxxxxxxx> wrote:
> > On Tue, 2009-06-23 at 12:56 -0600, Kirk.Johnson@xxxxxxxxxxx wrote:
> >> Andres Gonzalez <andres@xxxxxxxxxxxxxxx> wrote on 06/23/2009 12:26:38 PM:
> >>
> >> > I want to modify $results within the foreach. In other words,
> >> > during a given pass of this iteration, I want to delete some
> >> > of the items based on particular conditions. Then on the next
> >> > pass thru the foreach, I want $results to be the newer, modified
> >> > array.
> >> >
> >> > This does not seem to work. It appears that the foreach statement
> >> > is implemented such that $results is read into memory at the start
> >> > so that any modifications I make to it during a given pass, are ignored
> >> > on the next pass. Is this true?
> >>
> >> foreach works on a copy of an array, so the behavior you saw is expected.
> >> See the online manual.
> >>
> >> You could use a while loop, or, instead of unset-ing elements of $results,
> >> store the elements you want to keep into a new array.
> >>
> >> Kirk
> >
> > What about passing it by reference?
> >
> > foreach($results as &$key => &$item)
> > {
> >    // modify items here
> > }
> >
> > Thanks
> > Ash
> > www.ashleysheridan.co.uk
> >
> >
> > --
> > PHP General Mailing List (http://www.php.net/)
> > To unsubscribe, visit: http://www.php.net/unsub.php
> >
> >

Yeah, hehe, I was trying to remember off the top of my head, and
obviously forgot! :p

*slaps self*

Thanks
Ash
www.ashleysheridan.co.uk


-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux