I’m coding out a simple contact form, and the following code is giving me trouble:
if(!strlen($_POST['lastname']) > 0){
echo '<p class="message error">Please enter the parent\'s last name.</p>';
}
if(!strlen($_POST['comments']) > 5){
echo '<p class="message error">Please tell us a little more in the comments field.</p>';
}
Relevant form element:
<textarea name="comments" cols="60" rows="5"><?=(isset($_POST['comments']) ? $_POST['comments'] : '')?></textarea>
When I leave both fields blank, only the first error message (along with the others not shown) displays, whereas the one for the comments field does not.
The error checking even returns with an error if I submit the comments fields with less than 5 characters, as it should, but the error message does not print. In addition, I even echoed the strlen() of the comments field when I submitted with it blank and it prints out 0.
Can anyone see what the problem here is?
if (!strlen > 0)first evaluatesstrlen, which gives, say, 10. This is then negated by!tofalse. This is then compared to> 0, which isfalse, sincefalsewill be cast to0and0 > 0isfalse. The other way around, if the string is actually empty, the condition will betrue.You either want
if (!(strlen > 0))orif (strlen <= 0).