Collection iteration key removal in Hack

Collections in Hack are wonderful improvement over arrays, but there are a few scenarios that require work arounds. For example, a fatal error will be thrown if an index or key is removed from a collection during iteration. The error message looks something like the following: "HipHop Fatal error: Uncaught exception 'InvalidOperationException' with message 'Collection was modified during iteration'". This issue can be replicated with the following code.

$vector = Vector {1, 2, 3};
foreach ($vector as $i => $value) {
	// Do something
	$vector->removeKey($i);
}

Honestly, I'm not too sure how to solve this efficiently. For the time being, I've been using a secondary vector to log which indices need to be removed after the fact. Something like the following.

$vector = Vector {1, 2, 3};
$indices = Vector {};
foreach ($vector as $i => $value) {
	// Do something
	$indices[] = $i;
}
foreach ($indices as $i) {
	$vector->removeKey($i);
}

This scenario doesn't creep up too much, but it does occur. Any suggestions or better alternatives is appreciated.

2 Comments

  • I think It was because it was too long, anyways, You might want to see David Walsh's anti-spam technique. and about the article try
    $count = $vector->count();
    for($a=0;$a<$count;++$a){
    $vector->removeKey($a);
    }
    Steel Brain
  • I am unable to post a comment, it says Your comment has been denied and flagged as spam??
    Steel Brain