Refactor while loop to foreach loop.