replaced while with foreach