Change while loops with foreach