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.