php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Doc Bug #70594 behviour of unset inside foreach is undocumented
Submitted: 2015-09-28 01:14 UTC Modified: 2017-01-28 17:36 UTC
From: lucas at threeam dot com dot au Assigned:
Status: Open Package: Documentation problem
PHP Version: Irrelevant OS:
Private report: No CVE-ID: None
View Add Comment Developer Edit
Anyone can comment on a bug. Have a simpler test case? Does it work for you on a different platform? Let us know!
Just going to say 'Me too!'? Don't clutter the database with that please — but make sure to vote on the bug!
Your email address:
MUST BE VALID
Solve the problem:
34 - 11 = ?
Subscribe to this entry?

 
 [2015-09-28 01:14 UTC] lucas at threeam dot com dot au
Description:
------------
---
From manual page: http://www.php.net/function.unset
---

Does not explicitly mention whether a construct like

// Now delete every item, but leave the array itself intact:
foreach ($array as $i => $value) {
    unset($array[$i]);
}

is safe, even though it's implied since that example comes from a (non-user-contributed) note in http://www.php.net/language.types.array


You should probably also mention that this does not hold for 'for' loops unless the size of array is captured first. e.g. this is bad:

for ($i = 0; $i < count($a); $i++) {
    if (!sometest($a[$i])) {
        unset($a[$i]);
    }
}

but this is okay:

for ($i = 0, $n = count($a); $i < $n; $i++) {
    if (!sometest($a[$i])) {
        unset($a[$i]);
    }
}


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2017-01-28 17:36 UTC] cmb@php.net
In my opinion, the `foreach` man page should document whats
happening if elements/properties are added or removed
during the iteration.
 
PHP Copyright © 2001-2019 The PHP Group
All rights reserved.
Last updated: Tue Sep 17 06:01:29 2019 UTC