Re: Re: Possible foreach bug; seeking advice to isolate the problem

From: Date: Sat, 23 Oct 2010 14:56:52 +0000
Subject: Re: Re: Possible foreach bug; seeking advice to isolate the problem
References: 1 2 3 4 5  Groups: php.general 
Request: Send a blank email to php-general+get-309041@lists.php.net to get a copy of this message
On 23 October 2010 16:48, Jonathan Sachs <081012@jhsachs.com> wrote: > On Sat, 23 Oct 2010 08:34:27 +0200, peter.e.lind@gmail.com (Peter > Lind) wrote: > >>It is not a bug - somewhere before the foreach loop you've got, a >>variable is being referenced, and that's throwing things off. >>Otherwise, unsetting the variable would have no effect on the problem >>you're seeing. > > Could you please be more specific? "Somewhere... a variable is being > referenced" doesn't give me any insight into what is happening. > > It's absolutely clear to me WHERE the problem is. The first foreach > loop is causing the problem; I can prove this by removing it. But WHAT > the problem is, is absolutely unclear. I've studied this code every > which way, and I don't see how the first foreach loop can possibly > make the second one change the array -- unless it's a bug. > > I've boiled the script down to a couple of dozen lines that > demonstrate the problem without references to a database or to other > scripts. Having this to play with may help others give me some > insight. > > > <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> > <html> > <head> <title>foreach problem</title> </head> > <body> > > <?php >   $qs = array(); >   for ($i=0; $i<3; ++$i) { >      $qs[] = array($i); >   } > >   foreach ($qs as &$q) { >   } > >   echo $qs[0][0] . $qs[1][0] . $qs[2][0] . "<br>"; > >   foreach ( $qs as $q ) { >      echo $qs[0][0] . $qs[1][0] . $qs[2][0] . "<br>"; >   } > >   echo $qs[0][0] . $qs[1][0] . $qs[2][0] . "<br>"; > ?> > > </body> > </html> > You should read http://dk2.php.net/manual/en/control-structures.foreach.php - it points out the problem you're facing. More information (and a complete breakdown of your problem) is available here: http://schlueters.de/blog/archives/141-References-and-foreach.html It's not a bug - it's the effect you get when using references. Regards Peter -- <hype> WWW: plphp.dk / plind.dk LinkedIn: plind BeWelcome/Couchsurfing: Fake51 Twitter: kafe15 </hype>

« previous php.general (#309041) next »