Stop execution of code mid while loop

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Stop execution of code mid while loop

Post 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;
    }
?>
kettle_drum
DevNet Resident
Posts: 1150
Joined: Sun Jul 20, 2003 9:25 pm
Location: West Yorkshire, England

Post 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;
}
Post Reply