Input value 0 = empty?

▼魔方 西西 提交于 2019-12-22 01:17:00

问题


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?


回答1:


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) {



回答2:


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.




回答3:


Check for $value === null

if ($value === null && in_array($key, $required_fields) === true) {


来源:https://stackoverflow.com/questions/15571391/input-value-0-empty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!