Replaced for loop with foreach