Refactored to one foreach loop and one if statement