Change while loop to foreach