In programming having a loop inside a loop can be really common, this is how some variant of quicksort work, this should not be prevented, only fixed...
Maybe storing said variable in an array rather than a variable for a quick temp fix ?