Convert some loops into foreach loops