Replaced for loops by foreach

It also removes the assignment by reference and the multiple access of the static attribute when not necessary.