| 
        php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login | 
  [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)
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits             
             | 
    |||||||||||||||||||||||||||
            
                 
                Copyright © 2001-2025 The PHP GroupAll rights reserved.  | 
        Last updated: Tue Nov 04 12:00:01 2025 UTC | 
<?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 -