Changed last part into a for loop and a foreach loop