php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #40705 Iterating within function moves original array pointer
Submitted: 2007-03-03 12:31 UTC Modified: 2007-07-24 19:26 UTC
Votes:16
Avg. Score:5.0 ± 0.0
Reproduced:16 of 16 (100.0%)
Same Version:16 (100.0%)
Same OS:4 (25.0%)
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
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: avb@php.net
New email:
PHP Version: OS:

 

 [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 commitsRelated reports
 [2007-03-06 13:19 UTC] dmitry@php.net
The same as http://bugs.php.net/bug.php?id=40509
 [2007-03-19 19:59 UTC] ashnazg@php.net
Tested this example against the 5.2.1 zipfile from php.net on WinXP and the problem does occur.

Also tested it against the 5.2 snapshot (php5.2-win32-200703191630.zip) from php.net, on WinXP, and the problem seems to still exist.
 [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
This bug has been fixed in CVS.

Snapshots of the sources are packaged every three hours; this change
will be in the next snapshot. You can grab the snapshot at
http://snaps.php.net/.
 
Thank you for the report, and for helping us make PHP better.


 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Nov 21 11:01:29 2024 UTC