|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2010-11-25 18:38 UTC] 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
PatchesPull Requests
Pull requests:
HistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Sun Nov 16 13:00:02 2025 UTC |
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.