Jump to content

Is there a way to simplify this if statement


Merdok

Recommended Posts

I'm setting up some form validation, I need to check all of the required post variables from the form and if they are empty to add them to the $foundErrors variable.

 

So far I have this:

 

if ($_POST['usr_firstname']) {
$db_usr_firstname = $_POST['usr_firstname'];
} else {
$db_usr_firstname = $_POST['usr_firstname'];	
$foundErrors .= $db_usr_firstname;
}

 

This seems a really long winded way of doing it as obviously I need to do this for every required field. Is there a better way?

 

Ideally I'd like something like

 

$mandatory = 'usr_firstname', 'usr_surname', 'usr_username', 'usr_email' ;

 

and then check all the post variables, if its in the mandatory list and is empty then add it to the $foundErrors variable but still retain its own variable name (so the form field will remain populated).

 

Any ideas?

Something like this

$mandatory[] = "usr_firstname";
$mandatory[] = "usr_surname";
$mandatory[] = "usr_username";
$mandatory[] = "usr_email";

foreach($mandatory as $item) if(!isset($_POST[$item]) || empty($_POST[$item])) $errors[$item] = true;
if(count($errors) > 0) echo "You've got errors";
else {
// Continue with your script

}

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.