php.net |  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
Votes:12
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
Have you experienced this issue?
Rate the importance of this bug to you:

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

see reproduction code.

Reproduce code:
---------------
<?php
$foo = array( 'foo' => 'bar', 'dings' => 'dongs' );
foreach( $foo as $k => $k ) {}
var_dump( $foo );
?>
array(2) {
  ["foo"]=>
  string(5) "dings"
  ["dings"]=>
  NULL
}


Expected result:
----------------
array(2) {
  ["foo"]=>
  string(3) "bar"
  ["dings"]=>
  string(5) "dongs"
}



Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2004-12-16 11:41 UTC] derick@php.net
I don't think this was ever supposed to work. 
 [2004-12-16 13:07 UTC] derick@php.net
(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] derick@php.net
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] sniper@php.net
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:
[php]
$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"
);
*/

[/php]
 [2008-07-11 21:11 UTC] jani@php.net
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
ready.


 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Tue Mar 19 05:01:29 2024 UTC