Replace foreach with each() allowing for filter conditions