Sort if and loop