Change while to foreach loop