|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2004-12-16 12:26 UTC] dennis at inmarket dot lviv dot ua
Description:
------------
If you foreach an array with a reference (foreach $a as $x=>&$y), modifying $y, and then without it (foreach $a as $x=>$y), on the second time it will return incorrect results.
The sample code has two functions - each iterates over array with a reference to value and modifies it and then they foreach that array - first function without a reference, and the second - with a reference. The first function fails to iterate to the end of array. However, the print_r shows the array is ok.
Reproduce code:
---------------
function test1() {
$a = array('key1'=>'value1', 'key2'=>'value2', 'key3'=>'value3');
foreach($a as $k=>&$v) {
$v .= '0';
}
print_r($a);
foreach($a as $k=>$v) {
echo $k .'=' . $v . "\r\n";
}
}
function test2() {
$a = array('key1'=>'value1', 'key2'=>'value2', 'key3'=>'value3');
foreach($a as $k=>&$v) {
$v .= '0';
}
print_r($a);
foreach($a as $k=>&$v) {
echo $k .'=' . $v . "\r\n";
}
}
test1();
test2();
Expected result:
----------------
Array
(
[key1] => value10
[key2] => value20
[key3] => value30
)
key1=value10
key2=value20 <- all values properly changed
key3=value30
Array
(
[key1] => value10
[key2] => value20
[key3] => value30
)
key1=value10
key2=value20 <- all values properly changed
key3=value30
Actual result:
--------------
Array
(
[key1] => value10
[key2] => value20
[key3] => value30
)
key1=value10
key2=value20
key3=value20 <- SHOULD BE '30'
Array
(
[key1] => value10
[key2] => value20
[key3] => value30
)
key1=value10
key2=value20
key3=value30
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Fri Nov 21 15:00:01 2025 UTC |
No, it is NOT related no those bugs: here is a test case that proves that with no array modification two consecutive foreach loops give different results $a = array('key1'=>'value1', 'key2'=>'value2', 'key3'=>'value3'); foreach($a as $k=>&$v) { echo $k . '=' . $v . "\r\n"; } foreach($a as $k=>$v) { echo $k . '=' . $v . "\r\n"; } This produces this: key1=value1 key2=value2 key3=value3 key1=value1 key2=value2 key3=value2 <- must be 3