Question

Is this ok?


$error_msg = "";
if(!isset($_POST["name"]) || empty($_POST["name"])) {
  $error_msg="Not set name";
  exit();
} else if(!isset($_POST["radio1"]) || empty($_POST["radio1"])) {
  $error_msg="Not set question1";
  exit();
} else if(!isset($_POST["radio2"]) || empty($_POST["radio2"])) {
  $error_msg="Not set question2";
  exit();
} else { //... some code here }
//continues here after exit???
//Somewhere code printing first cahched error message

I'm not sure about behaviour of exit() here. What I wanna do is when i reach first condition fail, I set the $error_msg and exit the if, else if, else block and continue execution after it on line I marked "continues here after exit???" Where I print the error message and do other things like print the form etc.

Edit: To the reactions - I kind of thought it probably end the script but. So I know I was wrong,but my question was actually about what to do to end only "if else block". What will work for me? Something like break, return? Cause if if is not set name and radio2 the error message will be "Not set question2" instead of just "Not set name", cuz i wanna only first occured mistake.

Was it helpful?

Solution

No need for exit() remove them all. There is no need to "end" the if else block. Once any condition is met, it ends.

$error_msg = "";
if(!isset($_POST["name"]) || empty($_POST["name"])) {
  $error_msg="Not set name";
} else if(!isset($_POST["radio1"]) || empty($_POST["radio1"])) {
  $error_msg="Not set question1";
} else if(!isset($_POST["radio2"]) || empty($_POST["radio2"])) {
  $error_msg="Not set question2";
} else { 

    // Code to run if all post variables are set correctly.

}

if (!empty($error_msg)) {

    // Display error message - echo $error_msg;

}

OTHER TIPS

exit() will end the rest of the PHP script, you dont need to use it in this context.

The if statement will only process the else and else ifs if the condition(s) above it fails

Read this for more information on exit(): PHP.net Exit()

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top