5

Possible Duplicate:
php: ‘0’ as a string with empty()

I have an input in a form like so

<input name='var' type='number'>

When the form is submitted, input is sent to a PHP file through POST. On the PHP file, it checks to see if the input is filled out by checking

empty($_POST['var'])

When I enter '0' (zero) into the textbox and submit the form, the PHP code returns '1' for empty($_POST['var']) even though I have tried print_r($_POST) and 'var' clearly has the value of '0'.

Is this supposed to happen? Do I just need to also check for == 0 for this exception? Thanks.

Community
  • 1
  • 1
ansonl
  • 786
  • 1
  • 13
  • 34
  • 1
    Yep, [that's documented](http://us2.php.net/manual/en/function.empty.php). Zero is an "empty" value in string, int, and float forms. – Michael Berkowski Oct 24 '12 at 02:04
  • 2
    If you need to code around the zero case, use `if (empty($_POST['var']) && !is_numeric($_POST['var']))` – Michael Berkowski Oct 24 '12 at 02:07
  • Thanks for the documentation link, didn't see that list before. :) Is there a way to mark your comment as the answer? – ansonl Oct 24 '12 at 02:34
  • 1
    You can't accept comment. Rather than answer, I have linked an already existing question that covers the same topic and +1'd yours. Yours may eventually be closed with a link to the other. – Michael Berkowski Oct 24 '12 at 02:41

3 Answers3

3

To check whether the field is filled or not, please use isset($_POST['var']) instead of empty($_POST['var']).

Fikri Fadzil
  • 139
  • 1
  • 7
  • It has its own caveats though. `isset()` will return `TRUE` on an empty string, which for the purposes of a `$_POST` key may not be the intended behavior. – Michael Berkowski Oct 24 '12 at 02:21
0

You can't use empty only to check whether it is empty string or string only contains blank char.

Use like this:

function isEmpty($key) {
  return isset($_POST[$key]) && trim($_POST[$key]) === '';
}
xdazz
  • 158,678
  • 38
  • 247
  • 274
0

empty() returns true if the variable being checked is undefined, 0, empty string '', false, an empty array, or null. So the result you are seeing is 100% correct.

In the case where 0 is a legitimate value, use is_set().

Ray
  • 40,256
  • 21
  • 101
  • 138