Bug #73622 [Nab]: Foreach iteration with a previously initialized variable

From: Date: Thu, 01 Dec 2016 13:13:06 +0000
Subject: Bug #73622 [Nab]: Foreach iteration with a previously initialized variable
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-205711@lists.php.net to get a copy of this message
Edit report at https://bugs.php.net/bug.php?id=73622&edit=1 ID: 73622 User updated by: dorin dot marcoci at gmail dot com Reported by: dorin dot marcoci at gmail dot com Summary: Foreach iteration with a previously initialized variable Status: Not a bug Type: Bug Package: Scripting Engine problem PHP Version: 7.0.13 Block user comment: N Private report: N New Comment: The problem is that foreach performs differently. This script: <?php $A = new stdClass(); $A->Code = 'one'; $B = new stdClass(); $B->Code = 'two'; $H = [$A, $B]; $C = &$A; foreach ($H as $C) echo ' '.$C->Code; ?> Outputs: " one two", even if $C initially was a reference. BUT this one: <?php $A = new stdClass(); $A->Code = 'one'; $B = new stdClass(); $B->Code = 'two'; $H = [$A, $B]; foreach ($H as &$C); foreach ($H as $C) echo ' '.$C->Code; ?> Outputs: " one one", Surprise!. Previous Comments: ------------------------------------------------------------------------ [2016-12-01 07:22:24] a at b dot c dot de So you want variable references in this particular instance to behave differently from the way they behave in the rest of the language? Not gonna happen. ------------------------------------------------------------------------ [2016-11-30 09:24:00] dorin dot marcoci at gmail dot com OK, big red warning is not an excuse. This IS definitely a bug. When I do foreach($Array AS $VAR) then it should return in var a NEW $VAR instance in any way, was it used previously or not. ------------------------------------------------------------------------ [2016-11-30 09:12:43] requinix@php.net Please take note of the big red warning in the documentation. http://php.net/manual/en/control-structures.foreach.php ------------------------------------------------------------------------ [2016-11-30 09:09:03] dorin dot marcoci at gmail dot com Description: ------------ Script below output A A instead of A B. Is this as designed? If I do unset($Item) before second foreach then it works as expected. Test script: --------------- <?php $Items = [['Code' => 'A'], ['Item' => 'B']]; foreach ($Items as &$Item) $Item['Hash'] = rand(1, 10); foreach ($Items as $Item) echo ' '.$Item['Code']; Expected result: ---------------- A B Actual result: -------------- A A ------------------------------------------------------------------------ -- Edit this bug report at https://bugs.php.net/bug.php?id=73622&edit=1

« previous php.bugs (#205711) next »