Page 1 of 1

Stop execution of code mid while loop

Posted: Fri Dec 10, 2004 11:44 pm
by Benjamin
I have a while loop which validates data posted from a form. It is very extensive and can throw a lot of different errors, but I only want it to throw 1 error at a time, and stop validating data as soon as something fails validation.

Below is a small sample of the code. A problem I was having was that the entire loop would execute even after it encountered an error. This was not acceptable because the bottom of the loop ends by resetting the error to 0.

I tried a "do {} while;" loop but that did not work. The below code does work, but I had to add a break to every single line of code. Is there a better way to do this?

Code: Select all

<?php
  // ---------- D A T A     V A L I D A T I O N ---------- //
  while ($PostedDataError == -1)
    {
    // -------------------- CHECK MAXIMUM LENGTHS -------------------- //
    if (strlen($_POST['Password1']) > 24) {$PostedDataError = 45; break;}
    if (strlen($_POST['Password2']) > 24) {$PostedDataError = 46; break;}
    $PostedDataError = 0;
    }
?>

Posted: Sat Dec 11, 2004 2:27 am
by kettle_drum
Well using what you have already you can either nest the if statments, so the second one is only run if the first was ok, or add a check to see if you should set the $PostedDataError to 0 at the end.

Code: Select all

if($PostedDataError=-1){
   $PostedDataError = 0;
}