Moved flag variable outside foreach loop