php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #37715 array pointers resetting on copy
Submitted: 2006-06-06 15:27 UTC Modified: 2007-07-24 18:29 UTC
From: cmlburnett at gmail dot com Assigned: dmitry (profile)
Status: Closed Package: Arrays related
PHP Version: 5.1.4 OS: Linux 2.6
Private report: No CVE-ID: None
 [2006-06-06 15:27 UTC] cmlburnett at gmail dot com
Description:
------------
If I have an array of arrays and I iterate over the parent array with a foreach loop "foreach($a as $k => $d)" then the internal pointers of the subarrays will be reset.  I presume this is caused by copying $a[$k] into $d on each iteration.  It is also reproduced by simply doing an array copy "$c = $a".

Ultimately, this is an issue of array copying.

Reproduce code:
---------------
$a = array(
    'a' => array(
        'A', 'B', 'C', 'D',
    ),
    'b' => array(
        'AA', 'BB', 'CC', 'DD',
    ),
);

// Set the pointer of $a to 'b' and the pointer of 'b' to 'CC'
reset($a);
next($a);
next($a['b']);
next($a['b']);
next($a['b']);

var_dump(key($a['b']));
foreach($a as $k => $d)
{
}
// Alternatively $c = $a; and foreachloop removal will cause identical results.
var_dump(key($a['b']));


Expected result:
----------------
int(3)
int(3)

Having made no changes to $a I would expect nothing about $a to change.  As an end-user, if I'm making a *copy* of something then I would not expect the original to change and this would include internal state.  Really: I would prefer the pointer not change in the original and that the copy would retain the pointer as well.

Actual result:
--------------
int(3)
int(0)


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2006-06-06 15:32 UTC] tony2001@php.net
>Having made no changes to $a I would expect nothing about
> $a to change. As an end-user, if I'm making a *copy* of
> something then I would not expect the original to change
> and this would include internal state. 
I hope you don't expect to be able to make a copy without reading the original data - this is when the pointer is changed.
This is expected and not going to be changed.
 [2007-07-24 18:29 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: Mon Dec 30 14:01:28 2024 UTC