replace while/for to foreach