Replace for loop with foreach to work directly on array keys