Bug #70319 [Dup->Csd]: Foreach weird behaviour with references
| From: | bensor987 at neuf dot fr | Date: | Fri, 21 Aug 2015 13:27:10 +0000 |
| Subject: | Bug #70319 [Dup->Csd]: Foreach weird behaviour with references | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-195401@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=70319&edit=1
ID: 70319
User updated by: bensor987 at neuf dot fr
Reported by: bensor987 at neuf dot fr
Summary: Foreach weird behaviour with references
-Status: Duplicate
+Status: Closed
Type: Bug
Package: Scripting Engine problem
Operating System: Irrelevant
PHP Version: Irrelevant
Block user comment: N
Private report: N
New Comment:
Nvm, got an explanation.
Previous Comments:
------------------------------------------------------------------------
[2015-08-21 13:23:59] nikic@php.net
Duplicate of https://bugs.php.net/bug.php?id=29992.
------------------------------------------------------------------------
[2015-08-21 13:17:10] bensor987 at neuf dot fr
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 this bug report at https://bugs.php.net/bug.php?id=70319&edit=1