php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #42306 current/next/prev/key usage on the same array as foreach() is looping
Submitted: 2007-08-15 09:19 UTC Modified: 2007-08-16 12:24 UTC
From: hannes dot magnusson at gmail dot com Assigned: dmitry (profile)
Status: Not a bug Package: Arrays related
PHP Version: 5CVS-2007-08-15 (CVS) OS: Linux/Ubuntu 7.04
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: hannes dot magnusson at gmail dot com
New email:
PHP Version: OS:

 

 [2007-08-15 09:19 UTC] hannes dot magnusson at gmail dot com
Description:
------------
If I use current/next/prev/key() on the same array as foreach() is currently looping over the internal pointer is only increased on the first iteration.

However. If I compare the value ($b) to something before using current/next/prev/key() I get the expected results:

$a = range(0, 10);
foreach($a as $b) {
    if($b == 5) {
        var_dump(current($a)); // int(6)
    }
}



Reproduce code:
---------------
<?php
$a = range(0, 10);
foreach($a as $b) {
    var_dump(current($a));
    if($b == 5) {
        var_dump(current($a));
    }
}

Expected result:
----------------
int(1)
int(2)
int(3)
int(4)
int(5)
int(6) // The var_dump() inside the if()
int(6)
int(7)
int(8)
int(9)
int(10)
bool(false) // Since the internal pointer points beyond the end


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


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2007-08-15 10:32 UTC] jani@php.net
<?php
$a = range('a', 'f');
echo "without reference:\n";
foreach($a as $b) {
    echo key($a), ' - ', current($a), "\n";
}
echo "with reference:\n";
foreach($a as &$b) {
    echo key($a), ' - ', current($a), "\n";
}
?>

Output:

without reference:
1 - b
1 - b
1 - b
1 - b
1 - b
1 - b
with reference:
1 - b
2 - c
3 - d
4 - e
5 - f
 - 

 [2007-08-16 12:24 UTC] dmitry@php.net
foreach may do iteration over a copy of variable and not variable itself, and it may change or may not change internal array pointer. So, the mixture of foreach with reset/current/key/next/prev/end/each functions may produces unexpected behavior.

I don't see any reason to mix these two iteration approaches use one or the other.

 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Sat Apr 19 08:01:26 2025 UTC