Some people ask about how to add or remove elements to an existing array or a different container when iterating over them using loops. The answer to that is that it likely won't be handled too well, and it expects that during loops the keys of a data structure will remain constant.
The best way to achieve something similar is to populate a new container during the loop. So do that instead.