php三元运算符在输入0时失败

use*_*447 3 php

以下代码工作正常,直到inQuantity收到零"0".收到零后,它将其评估为空,并输入空值而不是"0".如果输入"0.00",则评估为非空.

$_POST['inQuantity'] = (!empty($_POST['inQuantity'])) ? $_POST['inQuantity'] : NULL;
Run Code Online (Sandbox Code Playgroud)

以下代码生成相同的结果

    if (empty($_POST['inQuantity'])) {
        $state = "empty";
    } else {
        $state = "full";
    }
Run Code Online (Sandbox Code Playgroud)

当inQuantity为"0"时,$ state的输出为"空"

谁知道为什么会这样?

Bar*_*rif 5

在这种情况下,您不应该使用empty,因为在这些情况下返回true 是标准的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)
Run Code Online (Sandbox Code Playgroud)

尝试使用isset():

$_POST['inQuantity'] = (isset($_POST['inQuantity'])) ? (float) $_POST['inQuantity'] : NULL;
Run Code Online (Sandbox Code Playgroud)