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
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: lucas at threeam dot com dot au
New email:
PHP Version: OS:

 

 [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-2018 The PHP Group
All rights reserved.
Last updated: Thu Jul 19 19:01:25 2018 UTC