Edit report at http://bugs.php.net/bug.php?id=53870&edit=1
ID: 53870
Comment by: akhrulev at mail dot ru
Reported by: lolbummer at gmail dot com
Summary: Problem with passing array elements as references in
foreach
Status: Open
Type: Bug
Package: Arrays related
Operating System: Mac OS X Snow Leopard
PHP Version: 5.3.5
Block user comment: N
Private report: N
New Comment:
I propose simplest testcase. It is reproduced on all my computers:
PHP 5.3.6 on Windows 7
PHP 5.3.5 on Windows XP
PHP 5.2.6 on Linux version 2.6.18-128.1.6.el5.centos.plus
<?php
$a = array( 'AAA', 'BB', 'C' );
foreach( $a as & $value )
{}
foreach( $a as $value )
{}
print_r( $a );
?>
Expected result:
Array
(
[0] => AAA
[1] => BB
[2] => C
)
Actual result:
Array
(
[0] => AAA
[1] => BB
[2] => BB
)
Previous Comments:
------------------------------------------------------------------------
[2011-02-04 16:04:38] uldericofilho at gmail dot com
On PHP 5.3.5 on CentOS 5.5 - same result. Proof of concept below:
echo "Result\n";
$arr = array(1,2,3,4,5);
foreach($arr as &$a){
$a*=2;
}
foreach($arr as $a){
echo $a."\n";
}
echo str_repeat('-', 10)."\nExpected\n";
$arr = array(1,2,3,4,5);
$arr = array_map(function($v){
return $v*2;
}, $arr);
foreach($arr as $a){
echo $a."\n";
}
------------------------------------------------------------------------
[2011-01-28 18:15:45] lolbummer at gmail dot com
Description:
------------
I created an array of strings that would be typecast to integers, and
cast them using a foreach loop, passing each element by reference.
After dumping the resulting array, it gave (somewhat) expected results,
though after dumping each element individually, it gave an unexpected
result on the last element.
This happened with PHP 5.3.5 on Mac OS X Snow Leopard, but did not
happen on a Debian system with PHP 5.2.6.
Test script:
---------------
<?php
$array = array('1', '2', '5324', '435', '51');
foreach($array as &$element){
$element = (int)$element;
}
var_dump($array);
foreach($array as $key => $element){
var_dump($key);
var_dump($element);
echo "\n";
}
?>
Expected result:
----------------
array(6) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
int(5324)
[4]=>
int(435)
[5]=>
int(51)
}
int(0)
int(1)
int(1)
int(2)
int(2)
int(3)
int(3)
int(5324)
int(4)
int(435)
int(5)
int(51)
Actual result:
--------------
array(6) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
int(5324)
[4]=>
int(435)
[5]=>
&int(51)
}
int(0)
int(1)
int(1)
int(2)
int(2)
int(3)
int(3)
int(5324)
int(4)
int(435)
int(5)
int(435)
------------------------------------------------------------------------
--
Edit this bug report at http://bugs.php.net/bug.php?id=53870&edit=1