Bug #53405 [Com]: accessing the iterator inside a foreach loop leads to strange results
| From: | chris at clowerweb dot com | Date: | Mon, 08 Apr 2013 23:39:38 +0000 |
| Subject: | Bug #53405 [Com]: accessing the iterator inside a foreach loop leads to strange results | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-178363@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=53405&edit=1
ID: 53405
Comment by: chris at clowerweb dot com
Reported by: jpauli@php.net
Summary: accessing the iterator inside a foreach loop leads
to strange results
Status: Assigned
Type: Bug
Package: Scripting Engine problem
Operating System: *nix
PHP Version: 5.3.3
Assigned To: dmitry
Block user comment: N
Private report: N
New Comment:
I actually experienced something last night during Wordpress development that I
believe to be related to this.
<ul>
<?php
$posts = get_posts();
foreach($posts as $post) {
setup_postdata($post); ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title();
?></a></li>
<?php } ?>
</ul>
Somehow the foreach loop was manipulating a $post (not $posts) variable in
another
part of the script, causing post pages to display incorrect content.
Previous Comments:
------------------------------------------------------------------------
[2010-11-25 18:38:12] jpauli@php.net
Description:
------------
foreach() is supposed to work on a copy of the iternal iterator.
However, manipulating the iterator inside the foreach loop leads to very strange results.
-> Also try to print the result of current() inside the foreach loop in the 3 use cases provided.
You'll see that the iterator is some kind of manipulated by foreach
Test script:
---------------
$a = range('a','d');
foreach ($a as $v) { }
var_dump(current($a));
$a = range('a','d');
foreach ($a as $v) { current($a); }
var_dump(current($a));
$a = range('a','d');
foreach ($a as &$v) { current($a); }
var_dump(current($a));
Expected result:
----------------
'a'
'a'
'a'
Actual result:
--------------
false
'b'
false
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=53405&edit=1