in reply to using foreach

Yep, it's just an iteration mishap that you have incurred. See 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).