moved foreach inside the if statement