php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #43501 foreach by reference corrupts the array
Submitted: 2007-12-05 08:37 UTC Modified: 2007-12-25 11:20 UTC
Votes:4
Avg. Score:5.0 ± 0.0
Reproduced:4 of 4 (100.0%)
Same Version:3 (75.0%)
Same OS:3 (75.0%)
From: gerry dot spm at gmail dot com Assigned: dmitry (profile)
Status: Not a bug Package: Scripting Engine problem
PHP Version: 5.2.3, 5.3CVS OS: Linux
Private report: No CVE-ID: None
 [2007-12-05 08:37 UTC] gerry dot spm at gmail dot com
Description:
------------
bug #29992 did not prove that the array was being modified by foreach, however this code does. According to var_dump() the last element starts as a "string" and after the foreach is a "reference to a string".

Reproduce code:
---------------
$foo = array('three', 'blind', 'mice');
var_dump($foo);
foreach($foo as &$elmnt){}
var_dump($foo);


Expected result:
----------------
array(3) {
  [0]=>
  string(5) "three"
  [1]=>
  string(5) "blind"
  [2]=>
  string(4) "mice"
}
array(3) {
  [0]=>
  string(5) "three"
  [1]=>
  string(5) "blind"
  [2]=>
  string(4) "mice"
}

Actual result:
--------------
array(3) {
  [0]=>
  string(5) "three"
  [1]=>
  string(5) "blind"
  [2]=>
  string(4) "mice"
}
array(3) {
  [0]=>
  string(5) "three"
  [1]=>
  string(5) "blind"
  [2]=>
  &string(4) "mice"
}

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2007-12-07 02:20 UTC] crrodriguez at suse dot de
Right, looks like it is wrong..

Dmitry, can you please check this out ? ;-)

--TEST--
Bug #43501 foreach by reference corrupts the array
--FILE--
<?php
$foo = array(0);
foreach($foo as &$elmnt){}
var_dump($foo);
?>
--EXPECT--
array(1) {
  [0]=>
  int(0)
}
 [2007-12-23 12:20 UTC] jani@php.net
Dmitry, can you check this out please?
 [2007-12-25 11:20 UTC] dmitry@php.net
This is not a bug but expected behavior.

After exit form "foreach" loop the $elmnt variable is still refer to the last element of array. To break the reference just do unset($elmnt) after "foreach" loop.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Apr 25 18:02:40 2024 UTC