|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #31114 foreach modify array (works with PHP 5.1)
Submitted: 2004-12-16 10:44 UTC Modified: 2008-07-11 21:11 UTC
Avg. Score:4.0 ± 1.7
Reproduced:8 of 11 (72.7%)
Same Version:4 (50.0%)
Same OS:2 (25.0%)
From: clemens at gutweiler dot net Assigned: andi (profile)
Status: Wont fix Package: Arrays related
PHP Version: 4CVS OS: Linux 2.4.27
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 — but make sure to vote on the bug!
Your email address:
Solve the problem:
29 + 3 = ?
Subscribe to this entry?

 [2004-12-16 10:44 UTC] clemens at gutweiler dot net
foreach modifies an array, if key and value are the same variable.

see reproduction code.

Reproduce code:
$foo = array( 'foo' => 'bar', 'dings' => 'dongs' );
foreach( $foo as $k => $k ) {}
var_dump( $foo );
array(2) {
  string(5) "dings"

Expected result:
array(2) {
  string(3) "bar"
  string(5) "dongs"


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2004-12-16 11:41 UTC]
I don't think this was ever supposed to work. 
 [2004-12-16 13:07 UTC]
(The only bug here is that it doesn't give a warning, using $k for both key and value is not supposed to work!)
 [2004-12-16 22:32 UTC]
I just tested this on PHP 4.3.1 and 4.3.2 and it behaves in the same way, making this a non-critical bug and not related to the foreach speed-up patch. Assigning to Andi, as he might have a clue why this happens. The new foreach code is definitely not the problem here.
 [2005-05-17 12:01 UTC]
Works fine in PHP 5..

 [2007-08-07 11:35 UTC] fedotov dot leon at gmail dot com
I stumbled across another werd behavior related to this bug:
$var = array(
  "a" => array("foo"),
  "b" => array("fox"),
  "c" => "x"

foreach($var as $key => $val) {
  echo "no matter what happends".$val; 
/* $var is array(
  "a" => array("foo"),
  "b" => array("fox"),
  "c" => "foo"

 [2008-07-11 21:11 UTC]
We are sorry, but we can not support PHP 4 related problems anymore.
Momentum is gathering for PHP 6, and we think supporting PHP 4 will
lead to a waste of resources which we want to put into getting PHP 6

PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Mon Apr 22 00:01:36 2024 UTC