Re: modifying within foreach
| From: | Andres Gonzalez | Date: | Tue, 23 Jun 2009 19:04:22 +0000 |
| Subject: | Re: modifying within foreach | ||
| References: | 1 2 3 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-294474@lists.php.net to get a copy of this message | ||
Thanks guys--passing by reference solved my problem. I was not aware
that the foreach statement works on a copy. This was explained in the
online documentation. Duh!!
Thanks again,
-Andres
Ashley Sheridan wrote:
On Tue, 2009-06-23 at 12:56 -0600, Kirk.Johnson@zootweb.com wrote:What about passing it by reference? foreach($results as &$key => &$item) {Andres Gonzalez <andres@packetstorm.com> wrote on 06/23/2009 12:26:38 PM: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. Kirkduring 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?I want to modify $results within the foreach. In other words,
// modify items here} Thanks Ash www.ashleysheridan.co.uk