migrate many `for` loops to `foreach`