Fix and improve foreach