2

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
  • Why not do a string comparison first? $test == "0" ? Commented Apr 28, 2011 at 5:10
  • if($value !== 0 ), because (false == 0) is true. but false === 0 is not true Commented Apr 28, 2011 at 5:10
  • The length of the string "0" is... (that is, ask PHP a different question) Commented Apr 28, 2011 at 5:14

3 Answers 3

2
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.)

Sign up to request clarification or add additional context in comments.

3 Comments

@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?
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. :)
0

Have you considered using is_null()?

if (is_null($value) || $value === "") {}

if (empty($value) && $value !== 0)

2 Comments

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
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"
0
if(!is_numeric($var) && empty($var))
{
    // empty
}
else
{
    // not empty
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.