Change while loop with foreach