Reputation: 2146
Okay, I know that there are a few of these questions already on SO; but they don't actually solve my problem.
For this (cut-down) html form:
<!DOCTYPE html><html><head><title>test</title></head><body>
<form method="post" autocomplete="on" action="application6.php">
<p>
<input type="text" name="fullname" id="fullname" maxlength="50" size="30">
<label for="fullname">*Full Name</label>
</p>
<p>
<input type="text" name="email" id="email" maxlength="50" size="30">
</p>
<p>
<select name="hours" id="hours">
<option value="" disabled="disabled" selected="selected">*Hours</option>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</p>
</body>
</html>
I have the following code
$error_array = array(
" "
);
echo ("debug: ");
print_r($_POST);
$variables = array(
'fullname',
'email',
'hours'
);
foreach ($variables as $variable_name) {
if (isset($_POST[$variable_name])) {
echo 'Variable: ' . $variable_name . ' is not set<br/>';
array_push($error_array, " " . $variable_name);
}
}
This results, in the submission of a blank form, in the output of
debug: Array ( [fullname] => [email] => )
An alternative is to check if these elements are empty(), but empty() will return false positives for when "hours" is set to 0.
Why are these elements incorrectly registering as being set, and what means can successfully test inputs of different types?
Upvotes: 0
Views: 1350
Reputation: 21671
Hi there is no need to check if isset because it will always be set you only need to check for this
if( trim($_POST['key']) != '' ){
}
Also if you really need to use the isset
$post = array_filter( array_map('trim', $_POST), function($a){
return $a != '';
});
That will remove them from $post
Upvotes: 0
Reputation: 279
if (isset($_POST[$variable_name])) {
echo 'Variable: ' . $variable_name . ' is set!!<br/>';
} elseif(!isset($_POST[$variable_name])){
array_push($error_array, " " . $variable_name);
} elseif( empty($_POST[$variable_name])){
echo 'Variable: ' . $variable_name . ' is empty!!<br/>';
} else{
var_dump($_POST[$variable_name])
}
Upvotes: 0
Reputation: 1440
The problem is in your logic, you check if $_POST[whatever] isset, and if so, you then output "Variable is NOT set" this is the opposite of what you're if statement checks. Try adding a ! in front of isset:
if (!isset($_POST[$variable_name])) {
echo 'Variable: ' . $variable_name . ' is not set<br/>';
array_push($error_array, " " . $variable_name);
}
Upvotes: 5
Reputation: 4544
try making sure the trimmed value is not an empty string and that the variable exists
foreach ($variables as $variable_name) {
if (isset($_POST[$variable_name]) && "" != trim($_POST[$variable_name]) ) {
echo 'Variable: ' . $variable_name . ' is not set<br/>';
array_push($error_array, " " . $variable_name);
}
}
Upvotes: 0