Refactor foreach