How do I write an if condition that will evaluate a zero as not empty? I'm writing a validation script and if the field is blank, I throw an error. In the case of a select with numerical values that start with 0 (zero), that should not considered to be empty. The manual states that a string 0 is considered to be empty and returns false. If I change empty to !isset, the zero works but the other textboxes that are truly empty pass validation. How do I write this to handle my case?
3 Answers
if (strlen($x)) {
// win \o/ (not empty)
}
Happy coding.
(All text box / form input content is inherently just text. Any meaning as a numerical value comes later and each representation can be validated. 0 is coerced back to "0" in strlen.)
3 Comments
jim
@pst.. I just tried strlen but a zero is being reported as "0" length. It shouldn't though right?
@jim See codepad.viper-7.com/6hVirM -- "works here". Perhaps there really is no 0?
jim
Ok, thanks for that my friend.. I have to have an issue somewhere else. Thanks for the help and the pointer of asking a different question. :)
Have you considered using is_null()?
if (is_null($value) || $value === "") {}
if (empty($value) && $value !== 0)
2 Comments
jim
Charles.. What I get with is_null is the exact same behavior that !isset gives me. Empty inputs now pass validation when they shouldn't
jim
Charles, here is what I get with is_null:
string(5) "aaaaa" string(0) "" string(0) "" string(0) "" string(0) "" string(4) "2222" string(5) "test1" string(0) "" string(1) "2"
$test == "0"?if($value !== 0 ), because(false == 0)is true. butfalse === 0is not true