Replace foreach with for