php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #64066 foreach with reference alter variable
Submitted: 2013-01-24 23:49 UTC Modified: 2013-01-25 00:12 UTC
From: w at ndrille dot fr Assigned:
Status: Not a bug Package: Testing related
PHP Version: 5.4.11 OS: Linux and Windows
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: w at ndrille dot fr
New email:
PHP Version: OS:

 

 [2013-01-24 23:49 UTC] w at ndrille dot fr
Description:
------------
When we use foreach with reference and use foreach again with the same variable 
without doing any action, php will alter array: The last value is doubled

Test script:
---------------
<?php
$a = array(1,2,3);
$z = $a;

foreach ($a as &$b){}
foreach ($a as $b){}

print_r($a);

if ($a != $z)
	print('bug');
?>

Expected result:
----------------
Array ( [0] => 1 [1] => 2 [2] => 3 )

Actual result:
--------------
Array ( [0] => 1 [1] => 2 [2] => 2 ) bug

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2013-01-25 00:12 UTC] tyrael@php.net
-Status: Open +Status: Not a bug
 [2013-01-25 00:12 UTC] tyrael@php.net
Sorry, but your problem does not imply a bug in PHP itself.  For a
list of more appropriate places to ask for help using PHP, please
visit http://www.php.net/support.php as this bug system is not the
appropriate forum for asking support questions.  Due to the volume
of reports we can not explain in detail here why your report is not
a bug.  The support channels will be able to provide an explanation
for you.

Thank you for your interest in PHP.

It is a documented behavior:
http://php.net/manual/en/control-structures.foreach.php
"Reference of a $value and the last array element remain even after the foreach 
loop. It is recommended to destroy it by unset()."
 
PHP Copyright © 2001-2021 The PHP Group
All rights reserved.
Last updated: Sat May 08 03:01:24 2021 UTC