php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #70319 Foreach weird behaviour with references
Submitted: 2015-08-21 13:17 UTC Modified: 2015-08-21 13:27 UTC
From: bensor987 at neuf dot fr Assigned:
Status: Closed Package: Scripting Engine problem
PHP Version: Irrelevant OS: Irrelevant
Private report: No CVE-ID: None
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: bensor987 at neuf dot fr
New email:
PHP Version: OS:

 

 [2015-08-21 13:17 UTC] 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)}


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2015-08-21 13:23 UTC] nikic@php.net
-Status: Open +Status: Duplicate
 [2015-08-21 13:23 UTC] nikic@php.net
Duplicate of https://bugs.php.net/bug.php?id=29992.
 [2015-08-21 13:27 UTC] bensor987 at neuf dot fr
-Status: Duplicate +Status: Closed
 [2015-08-21 13:27 UTC] bensor987 at neuf dot fr
Nvm, got an explanation.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sat Jun 01 16:01:31 2024 UTC