Input value 0 = empty?

2019-06-12 09:12发布

I have a page where you register your dog, and I want all these fields to be required:

$required_fields = array('name', 'age', 'gender', 'breed', 'size');
foreach ($_POST as $key => $value) {
    if (empty($value) && in_array($key, $required_fields) === true) {
        $errors[] = 'All fields marked with * are required.';
        break 1;
    }
}

The problem is, that if someone enters 0 (which I instruct them to do if the dog is a puppy), the submission seems to read that field as empty (giving me this error). I have checks further down removing any none integers etc., but the best solution and easiest form for users I still think is having them being able to enter 0 as a value. Anyway, is there any way I can make my php code read the value as not null?

3条回答
Fickle 薄情
2楼-- · 2019-06-12 09:32

From the manual:

The following things are considered to be empty:

"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)

A fix you may consider would be to do somethng like this:

if ((empty($value) && $value != 0) && in_array($key, $required_fields) === true) {
查看更多
叛逆
3楼-- · 2019-06-12 09:33

The PHP treats these as empty:

null
0
""
"0"
false

So you have two choices. Append something to it, like value a0 or, use isset.

查看更多
你好瞎i
4楼-- · 2019-06-12 09:53

Check for $value === null

if ($value === null && in_array($key, $required_fields) === true) {
查看更多
登录 后发表回答