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
Anyone can comment on a bug. Have a simpler test case? Does it work for you on a different platform? Let us know!
Just going to say 'Me too!'? Don't clutter the database with that please !
Your email address:
MUST BE VALID
Solve the problem:
46 - 7 = ?
Subscribe to this entry?

 
 [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 May 18 00:01:33 2024 UTC