Then as you run through the loop, save the last valid result (loopindex) to a variable.
It will save the first, valid set, then check again and if there is a higher set it will overwrite the previous result.
Do actions after your loop has completed, based on the stored value in the variable.