fixed infinite loops in foreach