Check all $_POST Variable at once
instead of checking all my post vari开发者_如何学Goables from a form one at a time is there any way to run one check to atleast verify that they are not empty something like
if(!isset(ALL $_POST)){
echo "one of your fields is not completed.";
}
You can create an array of required fields and loop through that
$required_fields = array("name", "address", "phone", "email");
foreach ($require_fields as $field) {
if (!strlen($_POST[$field])) {
echo "$field cannot be empty";
}
}
No because how would your program know which should exist?
However, if you have a list of fields that are expected, you can easily write a function to check. I called it array_keys_exist
because it does the exact same thing as array_key_exists
except with multiple keys:
function array_keys_exist($keys, $array) {
foreach ($keys as $key) {
if (!array_key_exists($key, $array)) return false;
}
return true;
}
$expectedFields = array('name', 'email');
$success = array_keys_exist($expectedFields, $_POST);
Can't be done like the way you're thinking (as PHP has no way of knowing what values there should be).
But you could it like this:
<?php
$POSTvaluesToCheck = array('write', 'here', 'all', 'the', 'values', 'that', 'are', 'mandatory', 'to', 'exist');
foreach($POSTvaluesToCheck as $key) {
if(!isset($_POST[$key]) {
echo $key . ' not set correctly!';
}
}
?>
精彩评论