Converted foreach to for loops