php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #62123 Foreach changes the internal pointer of the array strangely
Submitted: 2012-05-23 13:23 UTC Modified: 2012-05-24 01:47 UTC
From: a dot protaskin at gmail dot com Assigned:
Status: Not a bug Package: Arrays related
PHP Version: 5.4.3 OS: Linux
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: a dot protaskin at gmail dot com
New email:
PHP Version: OS:

 

 [2012-05-23 13:23 UTC] a dot protaskin at gmail dot com
Description:
------------
Traversing the array changes once the internal pointer by 1.
Traversing the array by link changes the internal pointer just as with each().

Test script:
---------------
<?php
$array = [0, 1, 2];
while (each($array)) {
    var_dump(key($array));
}

reset($array);
echo "----\n";

foreach ($array as $elem) {
    var_dump(key($array));
}

reset($array);
echo "----\n";

$array2 = &$array;
foreach ($array2 as $elem) {
    var_dump(key($array));
}

Expected result:
----------------
int(1)
int(2)
NULL
----
int(1)
int(2)
NULL
----
int(1)
int(2)
NULL

Actual result:
--------------
int(1)
int(2)
NULL
----
int(1)
int(1)
int(1)
----
int(1)
int(2)
NULL

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2012-05-23 21:54 UTC] nikic@php.net
See http://stackoverflow.com/a/8263425/385378 for an explanation.
 [2012-05-23 23:59 UTC] a dot protaskin at gmail dot com
Thanks for your answer, nikic. I understood this behaviour, this is not the bug.
 [2012-05-24 01:47 UTC] laruence@php.net
-Status: Open +Status: Not a bug
 [2012-05-24 01:47 UTC] laruence@php.net
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to report
a bug at http://bugs.php.net/how-to-report.php


 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Sat May 03 00:01:28 2025 UTC