RE: [PHP] foreach weirdness
| From: | Arno Kuhl | Date: | Fri, 23 Mar 2012 18:04:42 +0000 |
| Subject: | RE: [PHP] foreach weirdness | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-317224@lists.php.net to get a copy of this message | ||
-----Original Message-----
From: Robert Cummings [mailto:robert@interjinn.com]
Sent: 23 March 2012 06:11 PM
To: arno@dotcontent.net
Cc: php-general@lists.php.net
Subject: Re: [PHP] foreach weirdness
On 12-03-23 11:16 AM, Arno Kuhl wrote:
> The following snippet is copied from the php manual:
> foreach ($arr as $key => $value) {
> echo "Key: $key; Value: $value<br />\n"; }
>
> I've always used the foreach loop that way.
> But recently I started hitting some really odd problems.
>
> See this following example that illustrates the problem:
> $array = array(0, 1, 2, 3, 4, 5, 6);
> foreach ($array as $index=>&$value) { //<- assign $value by reference
> if ( ($index+1)< count($array) ) {
> $array[$index+1] += $value;
> }
> echo $value." ";
> }
> echo "<br />";
> foreach ($array as $index=>$value) {
> echo $value." ";
> }
>
> it still does not produce the correct result:
> 0 1 3 6 10 15 21
> 0 1 3 6 10 15 15
This looks like a bug... the last row should be the same. What version of PHP are you using? Have
you checked the online bug reports?
.....
--------------
Hi Rob
I'm using php 5.3.5. What result do you get when you run this code?
I haven't checked any bug reports, I'll google to see where I would do that.
Your code gets round the problem, but I was specifically referring to the use of foreach with its
unexpected side-effects. There are a few different designs like look-ahead where it seemed the
obvious way to go. I know I've used this type of foreach coding in the past, and have this
nagging feeling there's a whole bunch of code just waiting to explode. I always just assumed it
worked because it's pretty simple. I'd previously been caught out forgetting the assign by
reference in the foreach loop that modified the array but I always caught it long before it went
live, but I never considered having to also use assign by reference in subsequent foreach loops
because it so obviously wasn't necessary. Now I'm searching through my scripts to see if
there are any potential problems caused by this (already found one), and wondering what else
I've done where I no longer have access to the sources.
BTW I'm told on another forum this issue has been discussed multiple times on this mailing list
- did I miss it? Was there a resolution?
Cheers
Arno