|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2018-04-18 00:34 UTC] bmrgar at twc dot com
Description:
------------
After iterating through a key,value array with a while loop, subsequent loops through the same data fail.
Directly accessing array elements still works, as does cloning the array and looping through the new one (which will also fail after the first loop).
Test script:
---------------
$a = array("a"=>1,"b"=>2,"c"=>3);
print "\"a\" = ".$a["a"]."\n";
print "\"b\" = ".$a["b"]."\n";
print "\"c\" = ".$a["c"]."\n\n";
print "First loop:\n";
while (list($key,$value) = each($a)) { print "Key: \"$key\" = Value: $value\n"; } print "\n";
print "Second loop:\n";
while (list($key,$value) = each($a)) { print "Key: \"$key\" = Value: $value\n"; } print "\n";
print "Third loop (after copy of 'a' to 'b':\n";
$b = $a;
while (list($key,$value) = each($b)) { print "Key: \"$key\" = Value: $value\n"; } print "\n";
Expected result:
----------------
"a" = 1
"b" = 2
"c" = 3
First loop:
Key: "a" = Value: 1
Key: "b" = Value: 2
Key: "c" = Value: 3
Second loop:
Key: "a" = Value: 1
Key: "b" = Value: 2
Key: "c" = Value: 3
Third loop (after copy of 'a' to 'b':
Key: "a" = Value: 1
Key: "b" = Value: 2
Key: "c" = Value: 3
Actual result:
--------------
"a" = 1
"b" = 2
"c" = 3
First loop:
Key: "a" = Value: 1
Key: "b" = Value: 2
Key: "c" = Value: 3
Second loop:
Third loop (after copy of 'a' to 'b':
Key: "a" = Value: 1
Key: "b" = Value: 2
Key: "c" = Value: 3
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Fri Oct 24 07:00:01 2025 UTC |
For what it's worth, there is also the syntax foreach($a as $key=>$value) { ... } that can be used to implement "for each" loops. This syntax doesn't use the reset/next/each array pointer mechanism.