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
 [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

Pull Requests

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-2024 The PHP Group
All rights reserved.
Last updated: Sat Nov 23 10:01:28 2024 UTC