|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #76800 foreach inconsistent if array modified during loop
Submitted: 2018-08-27 08:29 UTC Modified: 2018-08-27 11:39 UTC
Avg. Score:3.0 ± 0.0
Reproduced:1 of 2 (50.0%)
Same Version:0 (0.0%)
Same OS:0 (0.0%)
From: leonix at motd dot ru Assigned: dmitry (profile)
Status: Closed Package: Arrays related
PHP Version: 7.2.9 OS:
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 this is not your bug, you can add a comment by following this link.
If this is your bug, but you forgot your password, you can retrieve your password here.
Bug Type:
From: leonix at motd dot ru
New email:
PHP Version: OS:


 [2018-08-27 08:29 UTC] leonix at motd dot ru
Hey. I encountered a weird inconsistency in foreach() behavior over plain arrays. See the code below. In certain specific cases loop will skip second iteration with no apparent reason.

It reproduces (at least) on 7.2.7-7.2.9 on both windows and linux, but NOT on 7.1.21 or below.

Test script:
$arr = [1 => 1, 3 => 3];           // [1 => 1, 2 => 3] will print both keys
foreach($arr as $key => &$val) {   // without & will print both keys
    echo "See key {$key}\n";
    $arr[0] = 0;                   // without this line will print both keys

Expected result:
See key 1
See key 3

Actual result:
See key 1


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2018-08-27 09:16 UTC]
-Status: Open +Status: Verified
 [2018-08-27 09:16 UTC]
Behavior confirmed: <> vs. <>.
 [2018-08-27 11:39 UTC]
-Assigned To: +Assigned To: dmitry
 [2018-08-27 11:39 UTC]
The regression seems to have been introduced with commit
31a2198[1].  Dmitry, could you please have a look?

[1] <;a=commit;h=31a2198>
 [2018-09-14 07:33 UTC]
Automatic comment on behalf of
Log: Fixed bug #76800 (foreach inconsistent if array modified during loop)
 [2018-09-14 07:33 UTC]
-Status: Verified +Status: Closed
PHP Copyright © 2001-2020 The PHP Group
All rights reserved.
Last updated: Wed Feb 19 14:01:28 2020 UTC