changed remove $key -= 1 to --$key