php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Doc Bug #43220 foreach modifies array pointer
Submitted: 2007-11-09 02:45 UTC Modified: 2007-11-12 10:56 UTC
Votes:8
Avg. Score:5.0 ± 0.0
Reproduced:8 of 8 (100.0%)
Same Version:7 (87.5%)
Same OS:7 (87.5%)
From: bugreporter at to dot mabomuja dot de Assigned: colder (profile)
Status: Closed Package: Documentation problem
PHP Version: 5.2.4 OS: Linux/Windows
Private report: No CVE-ID: None
View Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
If you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: bugreporter at to dot mabomuja dot de
New email:
PHP Version: OS:

 

 [2007-11-09 02:45 UTC] bugreporter at to dot mabomuja dot de
Description:
------------
In the code example below, when entering the for-loop, the arraypointer is at position 1 (the 2nd element).
When you comment out the foreach-loop before OR insert the reset-line, output starts - as expected - at the first array element (posistion 0).

This means "foreach" modifies the array pointer, although the documentation says "foreach operates on a copy of the specified array and not the array itself. Therefore, the array pointer is not modified"

Testing with versions 4.4.7/5.2.3/5.3dev(2007-11-08-Snap) of Windows zip package and 4.4.7/5.2.1 on gentoo (5.2.3 not testet on linux) shows correct behavior.

Reproduce code:
---------------
$t=range('a','c');

foreach ($t AS $key => $profil){
        $t[$key]="1";
}
//reset($t);
for ($i=0;$i<sizeof($t);$i++){
        echo key($t) . "->".current($t)."\n";
        next ($t);
}
print_r($t);


Expected result:
----------------
version 5.2.3:
0->1
1->1
2->1
Array
(
    [0] => 1
    [1] => 1
    [2] => 1
)

Actual result:
--------------
version 5.2.4:
1->1
2->1
->
Array
(
    [0] => 1
    [1] => 1
    [2] => 1
)

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2007-11-09 02:51 UTC] bugreporter at to dot mabomuja dot de
Actual Snaphots 5.3dev(2007-11-08-Snap) also has this bug and the code example is not working as i wrote above, sorry.
 [2007-11-09 13:31 UTC] felipensp at gmail dot com
The correct is: sizeof($t) - 1
 [2007-11-11 18:47 UTC] jani@php.net
Expected behaviour.
 [2007-11-12 10:56 UTC] colder@php.net
This bug has been fixed in the documentation's XML sources. Since the
online and downloadable versions of the documentation need some time
to get updated, we would like to ask you to be a bit patient.

Thank you for the report, and for helping us make our documentation better.


 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Wed Jul 30 18:00:02 2025 UTC