foreach - Remove element from Iterator in PHP -
i'm dealing class implements arrayaccess and iterator (let's $a
) and, while looping through foreach
, remove/unset elements (based on if
conditions).
foreach($a $item) { if(mustberemoved()) { $a->remove($item); } }
now, problem in implementation provoke unexpected behaviour in foreach
loop, cause not aware of changes , maintain going , stopping prematurely regardless element removed (or added).
is there good/elegant way solve issue?
just straigt forwards approach:
$tmp = array(); foreach($a $item) { if(!mustberemoved()) { $tmp[] = $item; } } $a = tmp;
collect items shouldn't removed , create new array. in end assign temporary array old one.
php foreach iterator arrayaccess
No comments:
Post a Comment