Bug #63179 [Dup]: foreach: Using variable reference leads to inconsistent data

From: Date: Sat, 29 Sep 2012 09:38:22 +0000
Subject: Bug #63179 [Dup]: foreach: Using variable reference leads to inconsistent data
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-173796@lists.php.net to get a copy of this message
Edit report at https://bugs.php.net/bug.php?id=63179&edit=1

 ID:                 63179
 User updated by:    uli dot staerk at globalways dot net
 Reported by:        uli dot staerk at globalways dot net
 Summary:            foreach: Using variable reference leads to
                     inconsistent data
 Status:             Duplicate
 Type:               Bug
 Package:            Scripting Engine problem
 Operating System:   Linux
 PHP Version:        Irrelevant
 Block user comment: N
 Private report:     N

 New Comment:

The manual says: "On each iteration, the value of the current element is assigned to
$value". 

This is not correct if you have a look at my example. The manual claims that an assignment happens,
but the reference has some magic override here.

Either you must fix this "consistent" implementation, or you have to fix the documentation
like "it will not be correctly assigned if $value is a reference".


Previous Comments:
------------------------------------------------------------------------
[2012-09-29 02:52:29] laruence@php.net

dup to #50485

------------------------------------------------------------------------
[2012-09-28 21:26:52] notzippy at gmail dot com

A variable that is the target of a foreach should be intrinsically unset and not need a manual
process to do it.

------------------------------------------------------------------------
[2012-09-28 15:16:44] uli dot staerk at globalways dot net

Description:
------------
As you can see from the example, php seems to mix up variables if you use the reference in a
foreach.

Despite the report bug 43806, I still think this is a bug. The variable must be set when calling
foreach and must not be influenced by any previous code.

Test script:
---------------
<?php
$testdata = array(
        0 => array('foo' => 'foo'),
        1 => array('bar' => 'bar')
);
foreach($testdata as &$value) {}
foreach($testdata as $key => $value) {
        if($key == 1) {
                print_r($value);
        }
}


Expected result:
----------------
Array
(
    [bar] => bar
)


Actual result:
--------------
Array
(
    [foo] => foo
)


------------------------------------------------------------------------



-- 
Edit this bug report at https://bugs.php.net/bug.php?id=63179&edit=1


Thread (7 messages)

« previous php.bugs (#173796) next »