Iterating within function moves original array pointer
| Bug #40705 | Iterating within function moves original array pointer | |||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Submitted: | 2007-03-03 12:31 UTC | Modified: | 2007-07-24 19:26 UTC |
|
||||||||||
| From: | avb@php.net | Assigned: | dmitry (profile) | |||||||||||
| Status: | Closed | Package: | Arrays related | |||||||||||
| PHP Version: | 5.2.1 | OS: | Irrelevant | |||||||||||
| Private report: | No | CVE-ID: | None | |||||||||||
[2007-03-03 12:31 UTC] avb@php.net
Description:
------------
If an array is passed by value to the function and is iterated over within said function, the "internal pointer" of the original array is moved.
Reproduce code:
---------------
function doForeach($array)
{
foreach ($array as $k => $v) {
// do stuff
}
}
$foo = array('foo', 'bar', 'baz');
doForeach($foo);
var_dump(key($foo));
Expected result:
----------------
int(0) (returned by versions prior to 5.2.1)
Actual result:
--------------
NULL (returned by version 5.2.1 and current 5.2 snapshot)
Patches
Pull Requests
History
AllCommentsChangesGit/SVN commits
[2007-03-19 19:59 UTC] ashnazg@php.net
[2007-05-03 10:24 UTC] jamesgauth at gmail dot com
This problem occurs in copies of an object's properties too. The array pointer is advanced by foreach in both the original and the copied variable. <?php class foo { var $arr = array(1, 2, 3); function test() { var_dump(key($this->arr)); $array_copy = $this->arr; foreach ($array_copy as $val) {} } } $a = new foo(); $a->test(); $a->test(); ?>[2007-07-24 19:26 UTC] dmitry@php.net