Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

PHP using exit() inside a function() to return only 1 value at a time

Suppose I have written the following function to check empty posted values:

function checkEmpty($postValue, $msg){
  if($postValue == null){
    return alert_danger($msg);
    exit(); // NOT WORKING AS EXPECTED
  }
}

And I am trying to call it for several input values this way:

echo checkEmpty($city, "City cannot be empty");
echo checkEmpty($phone, "phone cannot be empty");
echo checkEmpty($name, "name cannot be empty");

Now when I call this function above it echoes all the three values as it should be but I do not want that. I want it to return 1 error at a time. If city is empty it should return City cannot be empty only and not the others. When the user has corrected the error it should then proceed to check the next error. But it seems that the exit() used inside the function is not working as expected. I could use the following method:

if($name == null){
  echo alert_danger("Please enter your Name.");
  exit();
}

if($email == null){
  echo alert_danger("Please enter your Email ID.");
  exit();
}

if($phone == null){
  echo alert_danger("Please enter your Phone number.");
  exit();
}

But that makes the code too big unnecessarily if I have 15-20 variables to be checked. That's why I wanted to use the function method here as tried earlier. What should be the solution?

question from:https://stackoverflow.com/questions/66066857/php-using-exit-inside-a-function-to-return-only-1-value-at-a-time

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use a function that echoes the error then dies after:

function checkEmpty($postValue, $msg){
    if($postValue == null){
        echo alert_danger($msg);
        exit();
    }
}

checkEmpty($city, "City cannot be empty"); //without echo

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...