Tuesday, August 25, 2009

PHP to test for empty input, but not zero

PHP to test for empty input, but not zero
Wed, 19/04/2006
stuart

While writing my flash node I came across a problem with one field on the form. If it was empty I wanted to reset the value to the default, but zero was an allowed value.

In PHP empty($var) evalutes as true if $var is empty, but also if $var has a value of zero. So 0 was seen as empty and the default arrived.

Two solutions to test for empty, but not zero:

* Use if ( empty($var) && !is_numeric($var) )
* Use if ( $var == '' )

Both return true if empty and not zero. The latter looks easier to read. Not sure if one is any faster than the other! There's some discussion of this issue on php.net.

No comments: