in reply to using foreach
Better to use functions like pop and shift within while loops.
They are a cause of confusion, sometimes. Myself, in most instances, I usually tend to use normal iteration methods through a list/structure (mostly).