Bug #70319 [NEW]: Foreach weird behaviour with references
From: bensor987 at neuf dot fr
Operating system: Irrelevant
PHP version: Irrelevant
Package: Scripting Engine problem
Bug Type: Bug
Bug description:Foreach weird behaviour with references
Description:
------------
I've seen this on a reddit post, I thought it would be nice to put it
here.
There's a weird behaviour, when looping two times in an arrow, using
referenced values : the first loop will change the value of the last
element, with the same value as the previous one. See the example.
I've tested this with strings and arrays.
This behaviour is present since forever (including 7.0 RC1).
Test script:
---------------
<?php
// Strings
$data = array('a','b','c','d');
foreach ($data as $k => &$value) {}
foreach ($data as $value) {
echo $value;
}
// Arrays
$data = array(array(1,2),array(3,4),array(5,6),array(7,8));
foreach ($data as $k => &$value) {}
foreach ($data as $value) {
var_dump($value);
}
Expected result:
----------------
abcd
array(2){[0]=> int(1)[1]=> int(2)}
array(2){[0]=> int(3)[1]=> int(4)}
array(2){[0]=> int(5)[1]=> int(6)}
array(2){[0]=> int(7)[1]=> int(8)}
Actual result:
--------------
abcc
array(2){[0]=> int(1)[1]=> int(2)}
array(2){[0]=> int(3)[1]=> int(4)}
array(2){[0]=> int(5)[1]=> int(6)}
array(2){[0]=> int(5)[1]=> int(6)}
--
Edit bug report at https://bugs.php.net/bug.php?id=70319&edit=1
--
Try a snapshot (PHP 5.4): https://bugs.php.net/fix.php?id=70319&r=trysnapshot54
Try a snapshot (PHP 5.5): https://bugs.php.net/fix.php?id=70319&r=trysnapshot55
Try a snapshot (trunk): https://bugs.php.net/fix.php?id=70319&r=trysnapshottrunk
Fixed in SVN: https://bugs.php.net/fix.php?id=70319&r=fixed
Fixed in release: https://bugs.php.net/fix.php?id=70319&r=alreadyfixed
Need backtrace: https://bugs.php.net/fix.php?id=70319&r=needtrace
Need Reproduce Script: https://bugs.php.net/fix.php?id=70319&r=needscript
Try newer version: https://bugs.php.net/fix.php?id=70319&r=oldversion
Not developer issue: https://bugs.php.net/fix.php?id=70319&r=support
Expected behavior: https://bugs.php.net/fix.php?id=70319&r=notwrong
Not enough info: https://bugs.php.net/fix.php?id=70319&r=notenoughinfo
Submitted twice: https://bugs.php.net/fix.php?id=70319&r=submittedtwice
register_globals: https://bugs.php.net/fix.php?id=70319&r=globals
PHP 4 support discontinued: https://bugs.php.net/fix.php?id=70319&r=php4
Daylight Savings: https://bugs.php.net/fix.php?id=70319&r=dst
IIS Stability: https://bugs.php.net/fix.php?id=70319&r=isapi
Install GNU Sed: https://bugs.php.net/fix.php?id=70319&r=gnused
Floating point limitations: https://bugs.php.net/fix.php?id=70319&r=float
No Zend Extensions: https://bugs.php.net/fix.php?id=70319&r=nozend
MySQL Configuration Error: https://bugs.php.net/fix.php?id=70319&r=mysqlcfg
Thread (3 messages)
- bensor987 at neuf dot fr